TRT
Sign in
easyFoundationsLeetCode#open addressing#chaining

Design a hash map

Build put, get and remove for a hash map from scratch, without using your language's built-in hash table.

The Runtime Theory Team1 min read
Taught inCollisions: when two keys want the same slotTwo keys can land on the same slot. Linear probing stores the second one in the next free slot, and lookups follow the same path.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

input(1, 1); put(2, 2); get(1); get(3)

out1, -1

input(2, 1); get(2)

out1 (the value for key 2 was replaced)

inremove(2); get(2)

out-1

Implement a map from integer keys to integer values with three operations: put(key, value) inserts or replaces, get(key) returns the value or -1, and remove(key) deletes the key if present. Don't use your language's built-in hash table.

Before you code

Decide your collision strategy first. Chaining (an array of lists) is the easiest to get right. Linear probing is a better exercise: you will have to handle deletion without breaking lookups for keys stored further along.

Hints

  1. Pick a power-of-two capacity, such as 1,024, and compute the slot with a mask.
  2. With linear probing, a lookup stops at an empty slot, never at a tombstone.
  3. Count entries and grow the array when the load factor passes 0.75. Every key has to be inserted again, because its slot depends on the capacity.

Production & complexity notes

When solving Design a hash map on LeetCode (easy), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Collisions: when two keys want the same slot to reinforce the underlying pattern.

What it practices

The whole module in one exercise: slots, collisions and tombstones from Collisions: when two keys want the same slot, and growth from Resizing and load factor.

Not started

Sign in to save your learning progress.

Sign in to save