Algorithm patterns← All patterns

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
0
8
1
2
2
11
3
7
4
5
5
need = –target 9

seen: value → index

empty

Start with an empty map of value → index.

1 / 11
solution.ts
1function twoSum(nums: number[], target: number): number[] {
2 const seen = new Map<number, number>();
3 for (let i = 0; i < nums.length; i++) {
4 const need = target - nums[i];
5 if (seen.has(need)) return [seen.get(need)!, i];
6 seen.set(nums[i], i);
7 }
8 return [];
9}

Practice next