Consistent hashing ring
A free hard coding practice problem from databases. Solve it in JavaScript, TypeScript or Python and check your solution against fresh hidden tests — edge cases and random inputs — as often as you like.
- Difficulty
- Hard
- Type
- Function
- Topic
- Databases
- Languages
- JavaScript, TypeScript or Python
Problem
Shard keys across database nodes with a consistent-hash ring. Hash strings with 32-bit FNV-1a: start with h = 2166136261; for each character (all strings are ASCII) set h = h XOR charCode, then h = (h × 16777619) mod 2^32 (the hash of "a" is 3826002220).
- Every node places replicas points on the ring, at the hashes of node + "#" + i for i = 0 … replicas−1 (e.g. "db1#0", "db1#1").
- A key belongs to the node owning the first point whose position is ≥ the key's hash; if there is none, wrap around to the point with the smallest position.
- If several points share the chosen position, the node with the smallest name (character-code order) wins.
Return the owning node for each key, in order. There is at least one node and node names are distinct; 1 ≤ replicas ≤ 200, up to 50 nodes and 30 000 keys.
Function signature
// JavaScript
function assignKeys(nodes, replicas, keys)
// TypeScript
function assignKeys(nodes: any, replicas: any, keys: any): any
// Python
def assign_keys(nodes, replicas, keys):Examples
assignKeys(["db1","db2","db3"], 3, ["user:1","user:2","user:3","order:9"])→["db2","db2","db2","db1"]assignKeys(["solo"], 1, ["a","b"])→["solo","solo"]
How checking works
Run your code against the examples above, then submit a check: it runs on the server against hidden tests built fresh each time, including edge cases and random inputs. Practice is untimed and never affects a verified score; when you are ready, take a graded coding challenge to earn a badge.