Matching Receipts

Easyhash mapAlso known as Two Sum

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

You have the receipt amounts in the order you paid them. Find the two receipts your friend paid for.

Your task

Write findPair(amounts, target). Return the positions (indexes) of the two receipts whose amounts add up to target, 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, at positions 1 and 2. No other pair works: 40 would need a 60, and 15 an 85.

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

Two receipts can share an amount. 5 + 5 = 10, using positions 0 and 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 j for amounts[i] + amounts[j] === target.

It is correct, but pairs grow with n²: 10,000 receipts make about 50 million. The slow part is the inner loop searching 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