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
07
111
215
3Mapseen
empty
1/5
Narrationstep 1 of 5
Target sum = 9. Walk once; remember each value's index as we go.
Variables
target=9
i=—
result=—
How to think about it
- Translate the ask: find two indices i < j with nums[i] + nums[j] = target.
- Brute force compares every pair — O(n²).
- Observation: for each nums[i] the partner is fixed as target − nums[i]. Can we check 'has partner?' in O(1)?
- A hash map keyed by value → first-seen index gives O(1) lookup.
- 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