Two Sum
Find two distinct positions whose values add to the target. Return the pair with the smallest second index, then smallest first index. Return an empty array if no pair exists.
Find two distinct positions whose values add to the target. Return the pair with the smallest second index, then smallest first index. Return an empty array if no pair exists.
Input and constraints
- Use at most 32 integers. Each numeric input is between -1000 and 1000.
Code inspector
def solve(values, target): seen = [0] * (2001) i = 0 while (i < len(values)): need = (target - values[i]) if ((need >= -1000) and (need <= 1000)): if (seen[(need + 1000)] > 0): return [(seen[(need + 1000)] - 1), i] if (seen[(values[i] + 1000)] == 0): seen[(values[i] + 1000)] = (i + 1) i = (i + 1) return []Visualizer
Step 1 of 5Look for the earlier complement the current value
Look for the earlier complement 5.
Variable watch
Step explanation
Look for the earlier complement 5.
Worked explanation
At a ticket booth, remember who can provide the change you will need later.
Guided solution
As each value arrives, look up the earliest position of its complement. Store indices plus one so zero marks an unseen value.
O(n + U), U = 2001 time · O(U) auxiliary space
Enumerate earlier pairs
For each second index, inspect earlier entries from left to right.
O(n²) time · O(1) auxiliary space
Examples
Worked example · {"values":[4,1,7,2],"target":9} ⇒ [2,3]
Edge case 1 · {"values":[3,3],"target":6} ⇒ [0,1]
Edge case 2 · {"values":[],"target":2} ⇒ []
Edge case 3 · {"values":[1,4,6,9],"target":10} ⇒ [1,2]
Progressive hints
Hint 1
At a ticket booth, remember who can provide the change you will need later.Hint 2
As each value arrives, look up the earliest position of its complement. Store indices plus one so zero marks an unseen value.Hint 3
Step through the worked example and inspect the highlighted variables before each update.Common mistake
Looking up a complement after recording the current value can reuse the same item.
Interview follow-up
How would you return all matching index pairs?