Separate Chaining

Design HashMap

Easy
Solve it on LeetCode ↗

The problem

Implement a hash map (put, get, remove) for integer keys without using built-in hash table libraries.

Stuck? Reveal hints one at a time

How to approach it

  1. 1Choose a bucket count (e.g. 1009); hash(key) = key % buckets.
  2. 2put: scan the bucket’s chain; update the pair if the key exists, else append.
  3. 3get: scan the chain; return the value or −1.
  4. 4remove: filter the pair out of the chain.

Key insight

With load factor ≤ ~1, chains average O(1) length — the whole point of hashing is buying O(1) average ops with a fixed fan-out.

The solution

Watch out for

  • put on an existing key must UPDATE, not append a duplicate.
  • Array.from with a mapper is required — fill([]) would share ONE array across all buckets.