KatInterview

How Hash Tables Handle Collisions, Deletes, and Growth

Data Structure DesignModel answer
MediumModel answerData Structure Designhash-tablecollision-resolutionlinear-probing

Last updated

Walk through hash table internals: index mapping, chaining versus linear probing, safe deletion, load-factor resizing, and when operations degrade from O(1) to O(n).

Imagine you are asked to explain, from first principles, how a hash table is built and why its operations are usually constant time. Your explanation should compare two designs: separate chaining and open addressing with linear probing.

Cover the following areas.

  1. From key to slot. Describe how an arbitrary key becomes an array position. Include the modulo form and the bitmask form used when the capacity is a power of two. Explain why a table needs both a hashing routine and an equality check.

  2. Handling collisions.

    • How chaining organizes the entries that share a bucket (lists, arrays, balanced trees).
    • How linear probing finds another slot, and why quadratic probing and double hashing exist.
  3. Removing entries. Compare deletion in the two designs. Explain why blanking a slot is unsafe under linear probing, and describe two ways to fix it: tombstones and backward-shift deletion.

  4. Load factor and growth. Define the load factor, give typical resize thresholds for each design, justify why open addressing needs a lower one, and describe how a resize works. Explain why entries must be re-hashed rather than copied to their old positions.

  5. Cost analysis. Give average and worst-case time for insert, search and delete in both designs, plus space usage. Name realistic situations that produce the worst case, and compare the CPU cache behaviour of the two approaches.

A strong answer is structured, gives concrete numbers where they help, and points out common pitfalls.

Hints

Hint 1

Separate the problem into two steps: hash code generation, then compression to an index. Think about what information is lost when only the low bits are kept, and what the equality check resolves that the hash cannot.

Hint 2

For deletion under linear probing, ask what a lookup treats as proof that a key is absent. Then work out what happens to a key that was pushed past a slot that later gets emptied.

Hint 3

For load factor, compare the expected number of probes for linear probing as alpha approaches 1 with the expected chain length 1 + alpha. For resizing, ask what changes in the formula when the capacity changes, and use geometric growth to argue amortized cost.