Probabilistic Structures, Hashing & Geo-Indexing
The clever data structures behind large-scale systems — consistent hashing with virtual nodes and rendezvous hashing, Bloom and cuckoo filters, HyperLogLog, count-min sketch, heavy hitters and top-K, reservoir sampling, Merkle trees, skip lists and LSM trees, and geospatial indexing with geohash, quadtrees, S2 and H3.
Consistent hashing
import bisect, hashlib
class ConsistentHashRing:
def __init__(self, vnodes=150):
self.vnodes, self.ring, self.keys = vnodes, {}, []
def _h(self, s):
return int(hashlib.md5(s.encode()).hexdigest(), 16)
def add(self, node):
for i in range(self.vnodes):
h = self._h(f"{node}#{i}")
self.ring[h] = node
bisect.insort(self.keys, h)
def remove(self, node):
for i in range(self.vnodes):
h = self._h(f"{node}#{i}")
del self.ring[h]
self.keys.remove(h)
def get(self, key):
h = self._h(key)
i = bisect.bisect(self.keys, h) % len(self.keys) # wrap around
return self.ring[self.keys[i]]
Rendezvous hashing: for each key, score every node with hash(key, node) and pick the highest — no ring, perfectly even, O(N) per lookup (fine for small N). Jump hash: O(log N), no memory, but nodes can only be added/removed at the end.
Bloom filters
| Bits per element | Optimal k | False-positive rate |
|---|---|---|
| 5 | 3–4 | ~9% |
| 10 | 7 | ~0.8% |
| 15 | 10 | ~0.07% |
| 20 | 14 | ~0.007% |
Cuckoo filter: stores short fingerprints in a cuckoo hash table; supports deletion and better space efficiency at low FPR.
HyperLogLog
Cardinality estimation in ~12 KB with ~0.81% error, mergeable across time windows and shards.
PFADD visitors:2026-10-07 user_17 user_42 user_17
PFCOUNT visitors:2026-10-07 → 2
PFMERGE visitors:week visitors:2026-10-01 … visitors:2026-10-07
Count-min sketch and heavy hitters
import heapq, hashlib
class CountMinTopK:
def __init__(self, k, width=2000, depth=5):
self.k, self.w, self.d = k, width, depth
self.table = [[0] * width for _ in range(depth)]
self.heap, self.in_heap = [], {} # min-heap of (count, item)
def _idx(self, item, row):
return int(hashlib.blake2b(f"{row}:{item}".encode(), digest_size=8).hexdigest(), 16) % self.w
def add(self, item):
est = min(self._inc(item, r) for r in range(self.d))
if item in self.in_heap:
self.in_heap[item] = est
self.heap = [(self.in_heap[i], i) for i in self.in_heap]
heapq.heapify(self.heap)
elif len(self.heap) < self.k:
self.in_heap[item] = est
heapq.heappush(self.heap, (est, item))
elif est > self.heap[0][0]:
_, out = heapq.heapreplace(self.heap, (est, item))
del self.in_heap[out]
self.in_heap[item] = est
def _inc(self, item, row):
i = self._idx(item, row)
self.table[row][i] += 1
return self.table[row][i]
def top(self):
return sorted(self.heap, reverse=True)
Reservoir sampling picks a uniform random sample of k items from a stream of unknown length: keep the first k; for item i (> k), replace a random slot with probability k/i.
Merkle trees
Storage-engine structures
| Structure | Idea | Used in |
|---|---|---|
| Skip list | layered linked lists, O(log n) search, simple concurrency | Redis sorted sets, LSM memtables |
| LSM tree | memtable → sorted SSTables → compaction; Bloom filter per SSTable | Cassandra, RocksDB, LevelDB |
| B+ tree | high-fanout balanced tree, leaves linked | PostgreSQL, MySQL InnoDB |
| Trie / radix tree | prefix sharing | typeahead, routing tables |
Geospatial indexing
| Geohash length | Cell size (approx.) |
|---|---|
| 4 | 39 km × 19.5 km |
| 5 | 4.9 km × 4.9 km |
| 6 | 1.2 km × 0.61 km |
| 7 | 153 m × 153 m |
| 8 | 38 m × 19 m |
| Approach | Strength | Weakness |
|---|---|---|
| Geohash (string prefix) | trivial to store in any KV/B-tree, Redis GEO | fixed cells, edge effects, distortion near poles |
| Quadtree | adapts to density | in-memory, rebalancing for moving objects |
| R-tree (PostGIS) | arbitrary shapes, polygons | update-heavy workloads cost more |
| S2 (Hilbert cells) | hierarchical, good coverings for regions | conceptually complex |
| H3 (hexagons) | uniform neighbour distances; great for aggregations | cells don't nest perfectly |
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.