KatInterview

Building a Cache-Friendly Lookup Table for a Hot Loop

Data Structure DesignModel answer
MediumModel answerData Structure Designhash-tableopen-addressingsimd

Last updated

Design a hash table for a performance-critical inner loop, covering collision strategy, memory layout, probing, load factor, prefetching, and how to benchmark it.

You are writing a compute kernel that performs millions of key lookups per second against a fixed set of integer keys. The lookup sits inside the hottest loop of the program, so every cache miss and every mispredicted branch matters.

Design the hash table that serves these lookups. In your answer, cover:

  1. Collision strategy. Open addressing or chaining? Justify the choice in terms of memory access patterns, not just asymptotic cost.
  2. Memory layout. How are keys, values and any metadata arranged in memory? How does the layout enable vectorized comparisons and contiguous reads, and what alignment do you use?
  3. Hashing and bit tricks. Which hash function do you use, and how do you derive the slot or group index and any small fingerprint from it without a modulo?
  4. Probe sequence and load factor. Which sequence do you follow after a collision, what maximum load do you allow, and why?
  5. Latency hiding. How would you use batching and software prefetching when the kernel looks up many keys in a row?
  6. Trade-offs and validation. What does your design give up (deletions, resizing, memory overhead, adversarial inputs), and how would you profile and verify it, both for correctness and for speed?

You may assume lookups vastly outnumber inserts, so a build-then-read model is acceptable. Include a short code sketch of the table structure and its lookup path.

Hints

Hint 1

Think about what a lookup really costs on hardware: dependent loads to unpredictable addresses (cache misses) and unpredictable branches usually dominate, not the operation count.

Hint 2

Consider storing a one-byte fingerprint per slot in its own contiguous array, grouped so that one vector compare checks 16 slots at once, and only touch the full keys on a fingerprint match.

Hint 3

Take the group index and the fingerprint from different bit ranges of a well-mixed 64-bit hash so they stay independent, and use a power-of-two table so masks and shifts replace modulo.

Hint 4

A single lookup is latency-bound, but a batch is not: compute all hashes first, then prefetch the lines needed for key i + D while probing key i.