Pattern 04 / 10 · Fundamentals
Hash Map
Remember what you have seen so the answer is one lookup away.
The idea
Trade memory for time. As you scan, store each value (or its count, or its index) in a map. For every new item, the partner you need is a constant-time lookup instead of another loop.
time O(n)space O(n)
Reach for it when
- You keep asking “have I seen this before?” or “where was it?”.
- You need to count, group or pair items quickly.
- A nested loop is only there to search for a matching value.
Watch it run
1. Two Sum
Return the indices of the two numbers that add up to target.
Example 1
Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2
Input: nums = [3, 2, 4], target = 6
Output: [1, 2]
Example 3
Input: nums = [3, 3], target = 6
Output: [0, 1]
WALKTHROUGH INPUT · nums = [3, 8, 2, 11, 7, 5], target = 9
3
08
12
211
37
45
5need = –target 9
seen: value → index
empty
Start with an empty map of value → index.
1function twoSum(nums: number[], target: number): number[] {2const seen = new Map<number, number>();3for (let i = 0; i < nums.length; i++) {4const need = target - nums[i];5if (seen.has(need)) return [seen.get(need)!, i];6seen.set(nums[i], i);7}8return [];9}