Matching Receipts

Easyhash mapAlso known as Two Sum

You went on a trip with a friend and paid for everything. Back home, your friend sends you money for exactly two of your receipts. The message only says the total: target.

You have a list of receipt amounts in the order you paid them. Which two receipts was your friend paying for?

Your task

Write findPair(amounts, target). Return the positions (indexes) of the two receipts whose amounts add up to target. You can return them in either order.

Each receipt can be used once. There is always exactly one correct pair.

findPair(amounts: int[], target: int) → int[] Any order of the returned list is accepted.

Examples

Example 1
Input
amounts = [40, 25, 75, 15]
target = 100
Output
[1, 2]
Why

25 + 75 = 100. Those receipts sit at positions 1 and 2. No other pair works: 40 would need a 60, and 15 would need an 85.

Example 2
Input
amounts = [5, 5]
target = 10
Output
[0, 1]
Why

Two different receipts can have the same amount. 5 + 5 = 10, using position 0 and position 1. Using position 0 twice would not count.

Constraints

  • 2 ≤ amounts.length ≤ 10,000
  • 1 ≤ amounts[i] ≤ 1,000,000
  • Exactly one pair of different positions adds up to target.
Start with brute force

Try every pair: for each position i, check every later position j and see if amounts[i] + amounts[j] === target.

It is correct, and a fine first step. But with 10,000 receipts that is about 50 million pairs, because the number of pairs grows with n². The slow part is the inner loop: it searches the whole list for a partner every time.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code