Skip to the content

Lesson 122 of 296

Hashing with Map and Set

What you will learn

  • What a hash table is and why lookups are O(1)
  • Choosing Map, Set or a plain object
  • Counting frequencies
  • Two Sum, Contains Duplicate, Top K Frequent Elements, Longest Consecutive Sequence
On this page

Hash tables

A hash table stores key-value pairs. A hash function turns each key into a number that says where to store it, so finding a key does not require searching: O(1) on average.

If two keys land in the same place (a collision), the table handles it, which is why the worst case is O(n). In practice, JavaScript's Map and Set are hash tables with O(1) average operations (Lesson 64).

The most important pattern in coding interviews: if you are searching for something inside a loop, put it in a Map or Set first. That turns O(n²) into O(n).

Two Sum

Problem (LeetCode 1): return the indexes of the two numbers that add up to target. There is exactly one answer; you cannot use the same element twice.
nums = [2, 7, 11, 15], target = 9 → [0, 1].

Brute force: check every pair: O(n²).

Optimal: for each number, the partner we need is target - num. Store numbers we have already seen in a Map from value to index. If the partner is in the Map, we are done.

TypeScript
function twoSum(nums: number[], target: number): [number, number] | null {
  const seen = new Map<number, number>();
  for (let i = 0; i < nums.length; i++) {
    const num = nums[i]!;
    const partnerIndex = seen.get(target - num);
    if (partnerIndex !== undefined) return [partnerIndex, i];
    seen.set(num, i);
  }
  return null;
}

Trace with [2, 7, 11, 15], target 9:

inumneedseen before checkingresult
027{}not found; store 2→0
172{2→0}found: [0, 1]

O(n) time, O(n) space.

Details: we check before storing, so a number cannot pair with itself. We compare with !== undefined because index 0 is falsy.

Contains Duplicate

Problem (LeetCode 217): return true if any value appears at least twice.

TypeScript
function containsDuplicate(nums: number[]): boolean {
  const seen = new Set<number>();
  for (const n of nums) {
    if (seen.has(n)) return true;
    seen.add(n);
  }
  return false;
}

O(n) time, O(n) space. One-line version: new Set(nums).size !== nums.length (but it cannot stop early).

Top K Frequent Elements

Problem (LeetCode 347): return the k most frequent elements.
nums = [1, 1, 1, 2, 2, 3], k = 2 → [1, 2].

Step 1: count frequencies with a Map.
Step 2: pick the k largest counts.

  • Sort the entries by count: O(n log n).
  • A heap of size k: O(n log k) (Lesson 140).
  • Bucket sort: O(n). A number can appear at most n times, so make an array of "buckets" where buckets[count] holds the numbers with that count. Then read from the highest count down.
TypeScript
function topKFrequent(nums: number[], k: number): number[] {
  const counts = new Map<number, number>();
  for (const n of nums) counts.set(n, (counts.get(n) ?? 0) + 1);

  const buckets: number[][] = Array.from({ length: nums.length + 1 }, () => []);
  for (const [num, count] of counts) buckets[count]!.push(num);

  const result: number[] = [];
  for (let count = buckets.length - 1; count > 0 && result.length < k; count--) {
    for (const num of buckets[count]!) {
      result.push(num);
      if (result.length === k) break;
    }
  }
  return result;
}

O(n) time, O(n) space.

Longest Consecutive Sequence

Problem (LeetCode 128): find the length of the longest run of consecutive numbers, in O(n). Order in the array does not matter.
[100, 4, 200, 1, 3, 2] → 4 (the run 1, 2, 3, 4).

Brute force: sort, then count runs: O(n log n). The problem asks for O(n).

Idea: put everything in a Set. A number starts a sequence only if num - 1 is not in the set. From each start, count upwards while the next number exists.

TypeScript
function longestConsecutive(nums: number[]): number {
  const set = new Set(nums);
  let longest = 0;
  for (const num of set) {
    if (set.has(num - 1)) continue;
    let length = 1;
    while (set.has(num + length)) length++;
    longest = Math.max(longest, length);
  }
  return longest;
}

Why is it O(n) even with a loop inside a loop? The inner while only runs from the start of each sequence, so every number is counted inside a while at most once in total. Looping over the Set (not the original array) also avoids repeated work for duplicates.

Map, Set or plain object?

NeedUse
"Have I seen this?"Set
Count or store something per keyMap
Keys that are numbers, objects or arrays turned into stringsMap (object keys are always strings)
Fixed small alphabetAn array of size 26 (Lesson 120)

Arrays cannot be Map keys by value ([1, 2] and [1, 2] are different objects). Convert them to a string key such as "1,2".

How to say it in an interview

"Hash maps and sets give average O(1) insert and lookup, so whenever I search inside a loop I index the data first, trading O(n) space for an O(n) solution. Two Sum stores each value's index and looks up target minus the current number before inserting it. Top K Frequent counts with a Map and then uses bucket sort for O(n), or a size-k heap. Longest Consecutive Sequence only starts counting from numbers whose predecessor is missing, so each number is visited a constant number of times."

Key words

WordMeaning
Hash tableA structure that finds values by key in about O(1)
Hash functionTurns a key into a storage position
CollisionTwo keys mapping to the same position
Frequency mapA Map from item to how many times it appears
Bucket sortPlacing items into buckets by a small number, such as their count

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.