Build a Type-Aware Key-Value Store from First Principles
Data Structure DesignModel answerLast 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
- Type representation — How does the store hold keys and values of unknown type? What information must a key carry alongside its raw bytes?
- 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?
- Equality — Should integer
1and string"1"be considered the same key? How does the store decide two keys are equal? - Collision resolution — What strategy do you use when two distinct keys land in the same bucket? Walk through the mechanics.
- 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?
- Resizing — How do you know when the table is too full, and what does growing it cost?
- 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is that a hash map normally relies on the compiler knowing the key type so it can wire up hashing and equality automatically. Removing that assumption forces you to make those relationships explicit at runtime. Everything else — collision resolution, resizing, persistence — is the same work you would do for a typed map, just with a little more plumbing.
1. The Type Descriptor
The right starting point is a small descriptor struct that travels with every key:
typedef struct {
const void *data; // pointer to raw key bytes
size_t size; // length in bytes
uint64_t (*hash_fn)(const void *data, size_t size);
int (*eq_fn)(const void *a, size_t a_size,
const void *b, size_t b_size);
} KeyDesc;
The store never inspects data directly — it always calls hash_fn and eq_fn through the descriptor. This is type erasure done explicitly rather than through a vtable or interface{}.
Critical contract: if eq_fn(a, b) == true then hash_fn(a) == hash_fn(b). The reverse need not hold (collisions are allowed), but the forward direction is a hard invariant. Violating it corrupts the map silently. Integer 1 and string "1" are distinct keys by default because a caller-supplied int_eq and string_eq will never return true for them; type identity is part of equality.
2. Hashing
For built-in types, provide stock hash functions: FNV-1a or xxHash over the raw bytes works well for strings and byte arrays; for integers, multiply by a large prime (Knuth's 2654435761) to spread low-entropy keys across buckets.
For composite or custom types, the caller passes their own hash_fn. The store's only job is to call it and take the result modulo the current bucket count.
Common mistake: using pointer identity (hash_fn = address of key) instead of value-based hashing. Two separately allocated strings with identical content would then hash differently and never match.
3. Bucket Layout and Collision Resolution
Separate chaining is simpler to reason about with variable-length keys and is the right default here. Each bucket is a linked list of entries:
typedef struct Entry {
void *key_copy; // store-owned copy of key bytes
size_t key_size;
uint64_t (*hash_fn)(...);
int (*eq_fn)(...);
void *value_copy; // store-owned copy of value bytes
size_t value_size;
struct Entry *next;
} Entry;
Lookup walks the chain for bucket hash_fn(key) % num_buckets, calling eq_fn at each node. Insert prepends if no match is found; if a match exists, it frees the old value copy and stores the new one (update semantics).
Open addressing is also viable and gives better cache behavior, but handling variable-length keys in a flat array requires either a level of indirection (store pointers, not inline bytes) or a separate heap region, which erases the cache benefit. Mention this trade-off and move on.
4. Storage and Ownership
The store must copy both key and value bytes on insert. Rationale: the caller might be passing a stack buffer or might free the original allocation after the call returns. Borrowing a raw pointer without copying is a use-after-free waiting to happen.
entry->key_copy = malloc(key_desc->size);
memcpy(entry->key_copy, key_desc->data, key_desc->size);
On deletion or overwrite, the store frees what it owns. On map_destroy, every entry in every chain is freed.
Mutation after insertion: if the caller mutates the original key bytes after inserting, the store's copy is unaffected — this is the correct behavior and a benefit of copying. If you borrowed instead, mutation would silently corrupt the hash invariant.
5. Resizing
Track num_entries and num_buckets. When the load factor (num_entries / num_buckets) exceeds ~0.75, double the bucket array and rehash every entry into the new array. The rehash is O(n) amortized, so the amortized cost of insert remains O(1).
new_buckets = calloc(2 * num_buckets, sizeof(Entry*))
for each old bucket:
for each entry in chain:
new_idx = entry->hash_fn(entry->key_copy, entry->key_size) % (2 * num_buckets)
prepend entry to new_buckets[new_idx]
free old bucket array (not the entries themselves)
Shrinking is optional; mention it as a memory optimization with the caveat that thrashing around the threshold is a real risk if not hysteresis-controlled.
6. Persistence Boundary
An in-memory map full of function pointers cannot be written to disk as-is — hash_fn and eq_fn are virtual addresses that mean nothing after a restart.
For persistence, serialize each entry as: [type_tag (1 byte)][key_size (4 bytes)][key bytes][value_size (4 bytes)][value bytes]. The type tag encodes which built-in descriptor to reload. On read, reconstruct the entry by looking up the descriptor for that tag and calling its hash_fn to place the entry in the right bucket.
Custom (caller-supplied) hash and equality functions cannot survive serialization without a registered name scheme — mention this as a design constraint the API should surface.
Complexity Summary
| Operation | Average | Worst (all keys collide) |
|---|---|---|
| Lookup | O(1) | O(n) |
| Insert | O(1) amortized | O(n) |
| Delete | O(1) | O(n) |
| Resize | O(n) amortized | — |
Space: O(n) for entries plus O(b) for the bucket array, where b grows with n.
Common Mistakes to Flag
- Forgetting that hash and equality must be consistent — this is the most common source of silent correctness bugs.
- Storing raw caller pointers instead of copies, leading to use-after-free.
- Conflating type coercion with key equality (treating
1and"1"as the same key without explicit design intent). - Skipping the resize path entirely and claiming O(1) lookup on a map that degrades to O(n) under load.