Lesson 4.4
Two sum with a map
7 min · 8 steps
Step 1 of 8 · Explanation
Problem: "Return the indexes of two numbers that add up to
target." Brute force checks every pair, O(n²).With a map, flip the question. For each number
x, its partner has to betarget - x. Ask the map: "have I seentarget - x?" If not, storexwith its index and move on. One pass, O(n).Step 2 of 8 · Predict the result
What does it return for
[3, 2, 4]and target6?function solution(nums, target) { const seen = new Map() for (let i = 0; i < nums.length; i++) { const need = target - nums[i] if (seen.has(need)) { return [seen.get(need), i] } seen.set(nums[i], i) }}[1, 2][0, 0][2, 1]
Step 3 of 8 · Predict the result
What does it return for
[3, 3]and target6?function solution(nums, target) { const seen = new Map() for (let i = 0; i < nums.length; i++) { const need = target - nums[i] if (seen.has(need)) { return [seen.get(need), i] } seen.set(nums[i], i) }}[0, 1][1, 1][0, 0]
Step 4 of 8 · Find the bug
This code looks for the indexes of two numbers that add up to
target. For[3, 2, 4]and target6, it returns[0, 0], but it should be[1, 2]. Tap the line that's in the wrong place.function solution(nums, target) { const seen = new Map() for (let i = 0; i < nums.length; i++) { seen.set(nums[i], i) const need = target - nums[i] if (seen.has(need)) return [seen.get(need), i] }}Step 5 of 8 · Trace the code
Fill in
iandneedat the marked steps, for[1, 5, 3, 7]and target10.function solution(nums, target) { const seen = new Map() for (let i = 0; i < nums.length; i++) { const need = target - nums[i] if (seen.has(need)) { return [seen.get(need), i] } seen.set(nums[i], i) }}solution([1, 5, 3, 7], 10)
Step 6 of 8 · Pick the approach
"Return the indexes of two numbers in
numsthat add up totarget." Constraints:2 ≤ nums.length ≤ 10⁵, exactly one answer, return the original indexes.
Which approach is right?- A Map from number to index, in one pass
- Every pair with two loops
- A Set of all the numbers
- Sort, then search from both ends
Step 7 of 8 · Arrange the code
A harder version: return how many pairs
(i, j)withi < jadd up totarget. The map holds counts, not indexes. One line doesn't belong.counts.set(x, (counts.get(x) || 0) + 1)}}return pairsfor (const x of nums) {pairs += counts.get(target - x) || 0function solution(nums, target) {let pairs = 0pairs += counts.has(target - x) ? 1 : 0const counts = new Map()Step 8 of 8 · Recap
- Flip the question: for each
x, look for atarget - xyou've already passed. - Check first, then store. That stops a number from pairing with itself.
- Store what the answer needs. Indexes for "where", counts for "how many".
- Flip the question: for each