Home / DSA / Lesson 3

Hash maps and sets

Beginner 8 min read Lesson 3 of 9

A hash table maps a key to a value using a hash function into buckets. Average insert/search/delete is O(1). Worst case is O(n) if everything collides — interviews usually want the average-case answer plus that caveat.

In JavaScript: object keys are strings (and symbols); Map keeps insertion order and allows any key type; Set stores unique values.

function twoSum(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);
  }
  return [];
}

Judge: Two Sum, First unique character. Pattern: HashMap patterns.