Skip Lists, Bloom Filters & Sketches
Randomised and probabilistic structures that trade a little certainty for big wins in speed and memory.
Some of the most-used structures in real systems are randomised or probabilistic: they accept a tiny chance of being slow or slightly wrong in return for simplicity, speed or massive memory savings.
Skip lists
A skip list is a sorted linked list with "express lanes". Each node is promoted to the level above with probability ½, so level k has about n/2ᵏ nodes. Searching starts at the top level and drops down when the next node would overshoot.
- Search, insert, delete: expected O(log n); range scans are just walks along level 1.
- Much simpler than balanced trees and easy to make concurrent (lock-free versions exist).
- Used by Redis sorted sets (ZSET), LevelDB/RocksDB memtables, and Java's
ConcurrentSkipListMap.
Bloom filters
A Bloom filter answers "is x in the set?" with either "definitely not" or "probably yes", using only a bit array and k hash functions — no stored elements.
- Add(x): set the k bits at
h1(x), …, hk(x). - Query(x): if any of those k bits is 0 → definitely absent. If all are 1 → probably present (could be bits set by other elements).
| Property | Value |
|---|---|
| False negatives | Never |
| False positives | Tunable: ~1% with ~9.6 bits per element and k = 7 |
| Deletion | Not supported (use a counting Bloom filter) |
| Memory | Independent of element size |
The optimal number of hash functions is , giving a false-positive rate of about .
import java.util.BitSet;
class BloomFilter {
private final BitSet bits;
private final int m, k;
BloomFilter(int m, int k) { this.bits = new BitSet(m); this.m = m; this.k = k; }
private int hash(String s, int i) {
int h1 = s.hashCode(), h2 = (h1 >>> 16) | 1;
return Math.floorMod(h1 + i * h2, m); // double hashing → k hashes
}
void add(String s) { for (int i = 0; i < k; i++) bits.set(hash(s, i)); }
boolean mightContain(String s) {
for (int i = 0; i < k; i++) if (!bits.get(hash(s, i))) return false;
return true;
}
}import hashlib
class BloomFilter:
def __init__(self, m: int, k: int):
self.m, self.k = m, k
self.bits = bytearray((m + 7) // 8)
def _hashes(self, s: str):
d = hashlib.sha256(s.encode()).digest()
h1 = int.from_bytes(d[:8], "big")
h2 = int.from_bytes(d[8:16], "big") | 1
return ((h1 + i * h2) % self.m for i in range(self.k))
def add(self, s: str):
for h in self._hashes(s):
self.bits[h // 8] |= 1 << (h % 8)
def might_contain(self, s: str) -> bool:
return all(self.bits[h // 8] & (1 << (h % 8)) for h in self._hashes(s))class BloomFilter {
private bits: Uint8Array;
constructor(private m: number, private k: number) {
this.bits = new Uint8Array(Math.ceil(m / 8));
}
private *hashes(s: string) {
let h1 = 2166136261, h2 = 0;
for (let i = 0; i < s.length; i++) {
h1 = Math.imul(h1 ^ s.charCodeAt(i), 16777619);
h2 = Math.imul(h2 + s.charCodeAt(i), 31);
}
h2 |= 1;
for (let i = 0; i < this.k; i++) yield (((h1 + i * h2) % this.m) + this.m) % this.m;
}
add(s: string) { for (const h of this.hashes(s)) this.bits[h >> 3] |= 1 << (h & 7); }
mightContain(s: string) {
for (const h of this.hashes(s)) if (!(this.bits[h >> 3] & (1 << (h & 7)))) return false;
return true;
}
}Where they're used: databases (Cassandra, RocksDB, HBase, Postgres) skip disk reads for keys that aren't in a file; CDNs avoid caching one-hit wonders; browsers checked malicious URLs; Bitcoin light clients.
Count-Min Sketch and HyperLogLog
- Count-Min Sketch — approximate frequency counts in a stream using a d × w grid of counters and d hashes; the estimate is the minimum of the d counters (only ever over-estimates). Used for heavy hitters and trending topics.
- HyperLogLog — estimates the number of distinct elements (cardinality) of billions of items in ~12 KB with ~1% error, by tracking the maximum number of leading zeros in hashed values. Redis
PFCOUNT, BigQueryAPPROX_COUNT_DISTINCT, "unique visitors" dashboards.
- Skip lists: randomised sorted lists with expected O(log n) operations; simpler and more concurrency-friendly than balanced trees.
- Bloom filters: no false negatives, tunable false positives, tiny memory — perfect for "skip work if definitely absent".
- Sketches (Count-Min, HyperLogLog) estimate counts and cardinalities over huge streams in fixed memory.
QHow would you check whether a username is taken across a billion users with minimal latency?medium
Put a Bloom filter in front of the database. If it says "definitely not present", the name is free with no DB hit. If it says "maybe", confirm with the database. False positives only cost an extra lookup.
QWhy does Redis use skip lists for sorted sets instead of balanced trees?medium
Comparable O(log n) performance, much simpler code, cheap range operations (ZRANGE) by walking level 1, and easy rank calculation by storing span widths on forward pointers.