Two Sum
Master this topic with zero to advance depth.
Two Sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Visual Representation
nums = [2, 7, 11, 15], target = 9
1. Complement = target - current
2. Scan through array:
- 2: Complement = 9-2 = 7. Not in map. Store {2: 0}
- 7: Complement = 9-7 = 2. FOUND in map at index 0!
Return [0, 1]Examples
Because nums[0] + nums[1] == 9, we return [0, 1].
Level I: Brute Force
Intuition
Try every possible pair of numbers in the array. This involves nested loops where the outer loop picks the first number and the inner loop looks for the second number that sums to the target.
Detailed Dry Run
nums = [2, 7, 11], target = 9
- i=0 (2), j=1 (7): 2+7=9. Found! Return [0, 1]
Level II: Sorting + Two Pointers
Intuition
If the array is sorted, we can use two pointers (left and right). If their sum is smaller than target, move left pointer right; if larger, move right pointer left. Note: Since we need indices, we must keep track of original positions.
Detailed Dry Run
nums = [3, 2, 4], target = 6
- Pairs with indices: [(3,0), (2,1), (4,2)]
- Sort: [(2,1), (3,0), (4,2)]
- L=0 (2), R=2 (4): sum=6. Found indices 1 and 2.
Level III: HashMap (One-Pass)
Intuition
Trade space for time. As we iterate, we calculate the complement needed (target - current). If complement is already in map, we found the pair. Otherwise, store the current number's index in the map.
Detailed Dry Run
nums = [2, 7, 11], target = 9
- n=2, comp=7. Map: {2: 0}
- n=7, comp=2. Map contains 2 (idx 0). return [0, 1]
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.