Build a persistent map like Immutable.js: a hash array mapped trie, structural sharing, collisions and deletes
Problem
Immutable.js, Clojure and Scala keep old versions of a map around for undo, time travel debugging and cheap === change checks, without copying the whole map on every update. Their maps are hash array mapped tries (HAMT): a wide tree indexed by the bits of each key's hash, where an update copies only the nodes on one root-to-leaf path and shares everything else with the old version.
const v1 = PersistentMap.empty().set("theme", "dark").set("lang", "en");
const v2 = v1.set("lang", "hi");
v1.get("lang"); // "en"
v2.get("lang"); // "hi"
v2.set("lang", "hi") === v2; // trueRef. UR-1445 · © UIRound · uiround.com/questions/build-a-persistent-map-like-immutable-js-a-hash-array-mapped-trie-structural-sharing-collisions-and-deletes
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 3
- code listings
- 6
- edge cases
- 5
- follow-up questions
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1Copying a whole Map on every set makes keeping old versions cost O(n) each. Instead, build a tree where each level picks a child by 5 bits of the key's hash, and a set copies only the nodes on the path from the root to the key.
Try it in the editor
Run your code as often as you like. Submitting it to the full test suite is part of Pro.
Private, and saved in this browser as you type. All your notes are on My lists.