Skip to content
DSA in JavaScript
← All patterns

Hash Map / Set Lookup

0/18 solved

What it is

Trade memory for speed: store what you have seen in a Map or Set so each lookup is O(1) instead of scanning again.

Used for

Two Sum, duplicates, frequency counts, grouping anagrams.
nums
2
7
11
15
seen
·

Step 1 of 5

Goal: find two numbers in [2, 7, 11, 15] that add up to 9. Checking every pair is slow. Trick: for a number x, the partner we need is 9 - x. If we remember every number seen so far, "have I seen the partner?" is answered instantly.

You see

  • Need "have I seen this?" in O(1)
  • Group by key (anagrams)
  • Count frequencies
  • Find a complement

Learn it in

Hash Map & Set (JS Map and Set)Polynomial Rolling HashHash TableLeast Recently Used (LRU) CacheBloom Filter

Template

function twoSum(nums, target) {  const idx = new Map();  for (let i = 0; i < nums.length; i++) {    if (idx.has(target - nums[i])) return [idx.get(target - nums[i]), i];    idx.set(nums[i], i);  }}

Practice problems