Hash maps · Easy
Two Sum
Return indices of two distinct elements that sum to target. Exactly one pair exists. Use two different positions and return the positions of the matching values.
Worked example
([2, 7, 11, 15], 9) → [0, 1]
- After seeing 2 at position 0, remember it.
- When you see 7, its complement is 9 − 7 = 2. Return [0, 1].
Python solution
def solve(nums, target):
seen = {}
for index, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], index]
seen[num] = indexLook up the complement before storing the current value so an element cannot pair with itself.
Time: O(n) expected · Space: O(n)