CodeArchon

easyArrays & HashingAmazonGoogleMetaAppleMicrosoft

Lost Receipt Pair Finder

You know the dinner total but lost the receipt. From a list of drink prices, find the two whose sum matches the bill.

Given an integer array `nums` and an integer `target`, return the two distinct indices whose values add up to the target. Exactly one solution is guaranteed, and the same element cannot be used twice.

Choose approach

2
0
7
1
11
2
15
3
Mapseen
empty
1/5
Narrationstep 1 of 5

Target sum = 9. Walk once; remember each value's index as we go.

1def find_pair(nums: list[int], target: int) -> list[int]:
2 seen: dict[int, int] = {}
3 for i, x in enumerate(nums):
4 need = target - x
5 if need in seen:
6 return [seen[need], i]
7 seen[x] = i
8 return []
Variables
target=9
i=—
result=—

How to think about it

  1. Translate the ask: find two indices i < j with nums[i] + nums[j] = target.
  2. Brute force compares every pair — O(n²).
  3. Observation: for each nums[i] the partner is fixed as target − nums[i]. Can we check 'has partner?' in O(1)?
  4. A hash map keyed by value → first-seen index gives O(1) lookup.
  5. Walk once; before storing nums[i], check for its partner.

Edge cases to catch in interview

  • Negative numbers — the arithmetic still works.
  • Duplicates — the second occurrence finds the first in the map (that's why we store before advancing).
  • Target = 2 · nums[i] with only one such element → the first occurrence won't match itself; the second will.

Examples

Example 1[0, 1]
{"nums":[2,7,11,15],"target":9,"values":[2,7,11,15]}

2 + 7 = 9.

Example 2[1, 2]
{"nums":[3,2,4],"target":6,"values":[3,2,4]}

2 + 4 = 6.

Example 3[0, 1]
{"nums":[3,3],"target":6,"values":[3,3]}

Both threes form the pair.

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed