Check each complement before saving the current value.
Problem trace
Look up the complement before storing the current index
Read it this way:For target 6 and input (3,3), the first 3 cannot match itself. The second 3 finds the earlier index 0 and returns distinct indices. Could index zero incorrectly match itself if its three were stored before the first lookup?
Sources and provenance
Full interview answer 21 min read
Find two input positions whose values add to one requested target sum.
Problem
Input. An integer list nums and an integer target.
Output. Return two zero-based indices [i, j] such that nums[i] + nums[j] == target.
Rules. The indices must differ; one position cannot supply both numbers.
Values may be negative or repeated, and the list may be empty.
Return any valid pair in either order, not the values or every pair.
Return [] if no pair exists. Leave nums unchanged.
Example. For nums = [3, 2, 4, 7] and target = 6, return [1, 2].
Those positions contain 2 and 4. For [3] and target 6, return [], not [0, 0].
Picture: Query Before Saving
Problem trace
Separate three-value input: lookup complement before storing its current index
Input and goalReturn the indices of two numbers that add to the target.
Initialize the lookupBefore index 0, seen is empty. Each retained value maps to one earlier index.
current i
0
example
nums = [3, 2, 4, 7], target = 6
target
6
Miss on the first complementAt i=0, num=3 and needed=6-3=3. The empty map has no 3, so the algorithm does not return.
arithmetic
not shown→6 - 3 = 3
branch
not shown→miss
lookup phase
next→miss
Save the first valueAfter the failed lookup, save 3 -> 0. Checking first is what prevents index 0 from pairing with itself.
key 3
not shown→index 0
invariant
not shown→seen contains exactly indices before the next cursor
lookup phase
miss→saved
Miss and save at index 1At i=1, num=2 and needed=6-2=4. Four is absent, so save 2 -> 1 and continue.
key 2
not shown→index 1
need 4
0→1
arithmetic
not shown→6 - 2 = 4
Find the saved complementAt i=2, num=4 and needed=6-4=2. The map contains 2 -> 1, so the two distinct indices are known.
The prompt asks for two positions whose values satisfy a target sum, so each current value determines one exact complement that can be looked up.
Keep true
Before processing index i, seen contains exactly the useful values from indices below i; therefore a hit is an earlier, distinct element.
Reuse it
When a current item determines one exact missing partner, store only prior facts needed to recognize that partner; this transfers to complement, difference, and prefix-sum lookup problems.
Before index 0, seen is empty. Each retained value maps to one earlier index. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why is the answer [1,2]? Why can index 0 not pair with itself?
Reference drawing
Problem trace
Look up the complement before storing the current index
Execution trace
Input and goalReturn the indices of two numbers that add to the target.
Initialize the lookupBefore index 0, seen is empty. Each retained value maps to one earlier index.
current i
0
example
nums = [3, 2, 4, 7], target = 6
target
6
Miss on the first complementAt i=0, num=3 and needed=6-3=3. The empty map has no 3, so the algorithm does not return.
arithmetic
not shown→6 - 3 = 3
branch
not shown→miss
lookup phase
next→miss
Save the first valueAfter the failed lookup, save 3 -> 0. Checking first is what prevents index 0 from pairing with itself.
key 3
not shown→index 0
invariant
not shown→seen contains exactly indices before the next cursor
lookup phase
miss→saved
Miss and save at index 1At i=1, num=2 and needed=6-2=4. Four is absent, so save 2 -> 1 and continue.
key 2
not shown→index 1
need 4
0→1
arithmetic
not shown→6 - 2 = 4
Find the saved complementAt i=2, num=4 and needed=6-4=2. The map contains 2 -> 1, so the two distinct indices are known.
The prompt asks for two positions whose values satisfy a target sum, so each current value determines one exact complement that can be looked up.
Keep true
Before processing index i, seen contains exactly the useful values from indices below i; therefore a hit is an earlier, distinct element.
Reuse it
When a current item determines one exact missing partner, store only prior facts needed to recognize that partner; this transfers to complement, difference, and prefix-sum lookup problems.
Before index 0, seen is empty. Each retained value maps to one earlier index. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why is the answer [1,2]? Why can index 0 not pair with itself?
Read it this way:For target 6 and input (3,3), the first 3 cannot match itself. The second 3 finds the earlier index 0 and returns distinct indices. Could index zero incorrectly match itself if its three were stored before the first lookup?
index
num
needed
seen before query
Result
0
3
3
{}
Save 3: 0
1
2
4
{3: 0}
Save 2: 1
2
4
2
{3: 0, 2: 1}
Return [1, 2]
Before each query, seen represents earlier values with strictly earlier indices.
One index per value suffices for one witness. Overwriting after a miss preserves that guarantee.
The trace’s i is the code’s index.
Code
def two_sum(nums: list[int], target: int) -> list[int]: seen: dict[int, int] = {} for index, num in enumerate(nums): needed = target - num if needed in seen: return [seen[needed], index] seen[num] = index return []
Expected time is O(n) under usual dictionary/unit-cost arithmetic assumptions; auxiliary space is O(n).
[3], target 6, returns []; [3, 3] returns [0, 1].
Change 1: Count Index Pairs
New task. Count distinct unordered index pairs.
Picture and change. Store prior frequencies; query before incrementing.
Code.
def count_pairs(nums, target): counts = {} answer = 0 for value in nums: answer += counts.get(target - value, 0) counts[value] = counts.get(value, 0) + 1 return answer
Check.[3, 3, 3], target 6, adds 0, 1, 2: total 3. A single 3 gives 0.
Use when. Multiplicity matters without emitting indices.
Change 2: Emit Every Pair
New task. Return all original-index witnesses.
Picture and change. Keep every earlier matching index, not one representative.
Code.
def all_pairs(nums, target): seen = {} answer = [] for index, value in enumerate(nums): for earlier in seen.get(target - value, []): answer.append([earlier, index]) seen.setdefault(value, []).append(index) return answer
Store-first logic lets the lone 3 in [3] match itself. Query order enforces distinctness.
Transfer Check
Why may the reference overwrite repeated values but all_pairs may not?
Reasoned Answer
One earlier witness suffices for the reference. Enumeration must retain every matching position.
Output Size Changes the Cost
The counting variant retains expected O(n) time and O(n) auxiliary space.
For m returned pairs, enumeration takes expected O(n+m) time and O(n+m) total space, including output.
All-equal input can produce n(n−1)/2 pairs; no algorithm can materialize them in linear output space.
Empty input yields no witness, zero count and an empty enumeration.
Sorting changes position tracking and needs a different movement proof; it is not a drop-in replacement for this contract.
Compare prefix counting when stored objects become range boundaries rather than item positions.