KatInterview

Build a Type-Aware Key-Value Store from First Principles

Data Structure DesignModel answer
MediumModel answerData Structure Designhash-maptype-erasurecollision-resolution

Last updated

Design a hash map that supports keys and values of arbitrary types, covering hashing contracts, equality semantics, collision resolution, and memory ownership.

The Problem

You are building a general-purpose key-value store where neither the key type nor the value type is fixed in advance. A caller might store an integer key mapped to a string value, a byte-array key mapped to a struct, or any other combination. Your job is to design the data structure end-to-end and explain every non-trivial decision.

What You Should Address

  1. Type representation — How does the store hold keys and values of unknown type? What information must a key carry alongside its raw bytes?
  2. Hashing — How do you compute a hash for an arbitrary key? What contract must a valid hash function satisfy, and who is responsible for providing it?
  3. Equality — Should integer 1 and string "1" be considered the same key? How does the store decide two keys are equal?
  4. Collision resolution — What strategy do you use when two distinct keys land in the same bucket? Walk through the mechanics.
  5. Storage and ownership — Keys and values may be variable-length. Who allocates and frees the memory? What happens when the same key is inserted twice?
  6. Resizing — How do you know when the table is too full, and what does growing it cost?
  7. Persistence boundary — If this store needs to survive a process restart, what changes?

Clarifying Questions to Consider

Before diving in, think about:

  • Are types known at compile time (generics/templates) or erased at runtime?
  • Can a key be mutated by the caller after insertion?
  • What is the expected ratio of reads to writes?
  • Does the store need to be thread-safe?

You do not need to write a fully working implementation, but pseudocode or code sketches for the trickiest parts (type descriptor, bucket lookup, resize) are expected.

Hints

Hint 1

Start with the hash/equality contract: a store cannot be correct if two keys that compare equal can produce different hashes. Lock that invariant down before touching memory layout.

Hint 2

Think about what a 'type descriptor' or 'key descriptor' struct needs to carry: a pointer to raw bytes, a length, a hash function pointer, and an equality function pointer. That four-field struct is the load-bearing piece of the whole design.

Hint 3

Variable-length keys make ownership non-trivial. Ask yourself: does the store copy the key on insert, or does it borrow a reference? If it borrows, what happens when the caller frees the original? Work through the double-insert case (update vs. replace) explicitly.