Versioned Key-Value Store with O(1) Snapshots
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Implement an in-memory versioned dictionary called SnapshotMap that captures point-in-time snapshots in constant time and answers historical lookups for any previously sealed snapshot.
Storage must stay proportional to actual state changes rather than keys * snapshots:
- Sparse per-key histories: keys left untouched during a snapshot window allocate zero extra records when a snapshot is sealed.
- Same-window write coalescing: repeated updates or deletions to the same key before the next snapshot is sealed overwrite that window's pending entry in place instead of appending multiple entries.
Support the following API on SnapshotMap:
__init__() -> None: Creates an empty map whose initial open snapshot window has ID0.put(key: str, val: int) -> None: Stores integervalunderkeyin the currently open window, replacing any earlier uncommitted change tokeyin that same window.get(key: str) -> Optional[int]: Returns the current value ofkey(including uncommitted edits in the open window), orNoneifkeyhas never been written or is currently deleted.delete(key: str) -> None: Markskeydeleted in the open window using a tombstone marker. Callingdeleteon a key that is already absent (get(key) is None) is a no-op and records nothing.take_snapshot() -> int: Seals the open window under its integer ID, increments the active window ID by1, and returns the ID that was just sealed (0,1,2, ...).get_snapshot(key: str, snap_id: int) -> Optional[int]: Returns the value associated withkeywhen snapshotsnap_idwas sealed, orNoneifkeywas absent or deleted then. RaisesValueErrorwheneversnap_id < 0orsnap_idis greater than or equal to the current open window ID.history_size(key: str) -> int: Returns the number of(snap_id, value_or_tombstone)records currently stored forkey(0ifkeywas never set).
Examples
Example 1
sm = SnapshotMap()
sm.put("cpu", 40)
sm.put("mem", 75)
sm.put("cpu", 55) # coalesces with 40 inside window 0
s0 = sm.take_snapshot() # -> 0
sm.put("cpu", 80)
sm.delete("mem")
s1 = sm.take_snapshot() # -> 1
sm.get("cpu") # -> 80
sm.get("mem") # -> None
sm.get_snapshot("cpu", s0) # -> 55
sm.get_snapshot("mem", s0) # -> 75
sm.get_snapshot("mem", s1) # -> None
sm.get_snapshot("disk", s0)# -> None
sm.history_size("cpu") # -> 2
Walk-through: Inside open window 0, writing 55 to "cpu" overwrites 40 in place, so sealing s0 = 0 captures {"cpu": 55, "mem": 75} with one record per key. In window 1, "cpu" advances to 80 while "mem" receives a tombstone, so sealing s1 = 1 leaves "mem" absent from snapshot 1 onward while preserving 75 in snapshot 0. "disk" was never inserted, so historical reads return None.
Example 2
sm = SnapshotMap()
sm.put("port", 8080)
sm.take_snapshot() # -> 0
sm.take_snapshot() # -> 1 (no writes in window 1)
sm.delete("port")
sm.take_snapshot() # -> 2
sm.put("port", 9090)
sm.take_snapshot() # -> 3
[sm.get_snapshot("port", i) for i in range(4)] # -> [8080, 8080, None, 9090]
sm.history_size("port") # -> 3
sm.get_snapshot("port", 4) # raises ValueError
Walk-through: Snapshot 1 modifies nothing, so "port" adds no new entry and snapshot 1 still resolves to 8080 from snapshot 0. Window 2 writes a tombstone (None), window 3 recreates "port" at 9090 (total 3 stored records across 4 snapshots), and querying snap_id = 4 fails with ValueError because window 4 has not been sealed yet.
Constraints
take_snapshot()must run inO(1)time.put(key, val)anddelete(key)must run inO(1)amortized average time.get(key)andhistory_size(key)must run inO(1)average time.get_snapshot(key, snap_id)must run inO(log H_k)time, whereH_k = history_size(key).- Total memory usage must be
O(K + U), whereKis the number of distinct keys ever written andUis the number of distinct(key, snap_id)windows in which a state change was recorded. - Keys are arbitrary strings;
valmay be any integer, including0and negative values.
Step-by-step walkthrough
Understand snapshot windows, sparse histories, and coalescing
Think of time in
SnapshotMapas numbered windows starting at_active_snap_id = 0:Window 0 (active = 0) take_snapshot() -> 0 Window 1 (active = 1) take_snapshot() -> 1 put("cpu", 40) freezes window 0 put("cpu", 80) freezes window 1 put("mem", 75) =========================> delete("mem") =========================> put("cpu", 55) (overwrites 40) ("mem" gets a tombstone) active becomes 2get(key)always reads the latest state, including uncommitted writes in the currently open window.get_snapshot(key, snap_id)reads the frozen state as ofsnap_id(0 <= snap_id < _active_snap_id).- Sparse history: if
"port"is set in window0and untouched across later snapshots,"port"still stores only one record until modified again. - Write coalescing: if
"cpu"is written multiple times inside window0, all writes in that window collapse into one record for window0.
Why copying the dictionary on every snapshot fails
The obvious first try keeps a
currentdictionary and copiesdict(current)into a list every timetake_snapshot()is called. Historical reads are trivial (frozen[snap_id].get(key)), yet both core constraints break:- Snapshot time becomes
O(K)instead ofO(1), because copying100,000keys copies100,000entries even if nothing changed. - Space explodes to
O(K * S)instead ofO(K + U):100,000keys across10,000snapshots allocates a billion dictionary slots even if only a few keys changed per window.
Instead of copying the whole map per snapshot, flip the layout: keep one sorted change log per key, recording an entry only in windows where that key actually changes.
- Snapshot time becomes
Store parallel `(snap_ids, values)` lists and a tombstone object
Why can't
delete(key)simply deletekeyfrom our map? Because earlier frozen snapshots still needkey's old values! Instead,delete(key)records a tombstone — a special marker meaning"from this snapshot onward, key is absent unless set again later".We create
_TOMBSTONE = object()as a unique sentinel object so valid integer values like0or-1can never collide with it. For each key,_KeyHistorystores two parallel lists —snap_idsandvalues— so Python'sbisect_rightcan binary-searchsnap_idsdirectly without tuple-comparison overhead:from bisect import bisect_right from typing import Dict, List, Optional # Unique sentinel object marking "deleted in this snapshot" so integer values # like 0 or -1 can never be confused with a deletion marker. _TOMBSTONE = object() class _KeyHistory: """Sparse version log for a single key using parallel lists for binary search.""" def __init__(self) -> None: # snap_ids: strictly increasing snapshot IDs, e.g. [0, 3, 5] self.snap_ids: List[int] = [] # values: matching int or _TOMBSTONE at each index, e.g. [15, _TOMBSTONE, 42] self.values: List[object] = []Coalesce writes in place and freeze snapshots in O(1)
Both
putanddeletefunnel through one helper_record_change(key, value):- Look up (or create)
history = self._histories[key]. - Check the last recorded snapshot ID
history.snap_ids[-1]:- If it equals
self._active_snap_id, this key was already modified in the current window — overwritehistory.values[-1] = valuein place (coalescing). - Otherwise, append
self._active_snap_idandvalue. Becauseself._active_snap_idonly ever increments,history.snap_idsstays strictly increasing automatically!
- If it equals
For
delete(key), checkif self.get(key) is None: returnfirst. If the key has never been set, or its latest entry is already_TOMBSTONE, deleting it again changes nothing and writes no extra record. Andtake_snapshot()simply returnsself._active_snap_idand adds1— pureO(1)work!class SnapshotMap: def __init__(self) -> None: # ID of the open, mutable window; frozen snapshots are 0 .. _active_snap_id - 1 self._active_snap_id: int = 0 # Maps each key that was ever set to its _KeyHistory self._histories: Dict[str, _KeyHistory] = {} def _record_change(self, key: str, value: object) -> None: """Write or coalesce a value/tombstone in the current active snapshot window.""" history = self._histories.get(key) if history is None: history = _KeyHistory() self._histories[key] = history if history.snap_ids and history.snap_ids[-1] == self._active_snap_id: # Write coalescing: key was already modified in this window, so overwrite # in place rather than appending a second entry for the same snap_id. history.values[-1] = value else: # _active_snap_id only increases, so appending keeps snap_ids sorted. history.snap_ids.append(self._active_snap_id) history.values.append(value) def put(self, key: str, val: int) -> None: self._record_change(key, val) def get(self, key: str) -> Optional[int]: history = self._histories.get(key) if history is None: return None latest_value = history.values[-1] if latest_value is _TOMBSTONE: return None return latest_value # type: ignore[return-value] def delete(self, key: str) -> None: # If the key was never set, or its latest entry is already a tombstone, # skip writing so repeated deletes do not bloat history. if self.get(key) is None: return self._record_change(key, _TOMBSTONE) def take_snapshot(self) -> int: frozen_id = self._active_snap_id self._active_snap_id += 1 return frozen_id- Look up (or create)
Query frozen snapshots with `bisect_right`
Suppose key
"k"changed in snapshots1,4, and7, with values[10, 40, _TOMBSTONE], and_active_snap_idis9. What was"k"'s value at snapshotsnap_id? It is whichever entry has the largest recorded snapshot ID<= snap_id.bisect_right(snap_ids, snap_id)returns the insertion index after any existingsnap_id— which equals the count of recorded IDs<= snap_id. Subtracting1lands directly on the version we want:history.snap_ids = [ 1, 4, 7 ] history.values = [ 10, 40, _TOMBSTONE ] indices: 0 1 2 Query snap_id = 0: bisect_right([1,4,7], 0) = 0 -> idx = -1 -> key not written yet -> None Query snap_id = 4: bisect_right([1,4,7], 4) = 2 -> idx = 1 -> exact hit on 4 -> 40 Query snap_id = 6: bisect_right([1,4,7], 6) = 2 -> idx = 1 -> carried from 4 -> 40 Query snap_id = 8: bisect_right([1,4,7], 8) = 3 -> idx = 2 -> hit _TOMBSTONE -> NoneNotice why
bisect_leftwould be a bug onsnap_id = 4:bisect_left([1, 4, 7], 4)returns1, and1 - 1 = 0would step backward to snapshot1's stale value10! Also notice why uncommitted writes in the open window (snap_id == _active_snap_id) never leak into frozen queries:get_snapshotrejectssnap_id >= _active_snap_idup front, and for anysnap_id < _active_snap_id, an uncommitted entry at_active_snap_idsits strictly to the right ofbisect_right.def get_snapshot(self, key: str, snap_id: int) -> Optional[int]: # Reject negative IDs and the active (unfrozen) or future snapshot IDs. if snap_id < 0 or snap_id >= self._active_snap_id: raise ValueError( f"Invalid snap_id {snap_id}; frozen snapshot IDs are 0..{self._active_snap_id - 1}" ) history = self._histories.get(key) if history is None: return None # bisect_right returns the count of entries with recorded_id <= snap_id, # so subtracting 1 lands on the latest entry written at or before snap_id. idx = bisect_right(history.snap_ids, snap_id) - 1 if idx < 0: # Every recorded entry for this key happened after snap_id. return None recorded_value = history.values[idx] if recorded_value is _TOMBSTONE: return None return recorded_value # type: ignore[return-value] def history_size(self, key: str) -> int: history = self._histories.get(key) if history is None: return 0 return len(history.snap_ids)Full trace of Example 1
Operation _active_snap_id "cpu" (snap_ids : values) "mem" (snap_ids : values) --------------------- --------------- ------------------------- -------------------------- SnapshotMap() 0 (absent) (absent) put("cpu", 40) 0 [0] : [40] (absent) put("mem", 75) 0 [0] : [40] [0] : [75] put("cpu", 55) 0 [0] : [55] (coalesced) [0] : [75] take_snapshot() -> 0 1 [0] : [55] [0] : [75] put("cpu", 80) 1 [0, 1] : [55, 80] [0] : [75] delete("mem") 1 [0, 1] : [55, 80] [0, 1] : [75, _TOMBSTONE] take_snapshot() -> 1 2 [0, 1] : [55, 80] [0, 1] : [75, _TOMBSTONE]get("cpu")->80;get("mem")-> latest is_TOMBSTONE->None.get_snapshot("cpu", 0)->idx = 0->55.get_snapshot("mem", 0)->idx = 0->75.get_snapshot("mem", 1)->idx = 1->_TOMBSTONE->None.get_snapshot("disk", 0)->"disk"not in_histories->None.get_snapshot("cpu", 2)->2 >= _active_snap_id-> raisesValueError.
Complete solution
from bisect import bisect_right from typing import Dict, List, Optional # Unique sentinel object marking "deleted in this snapshot" so integer values # like 0 or -1 can never be confused with a deletion marker. _TOMBSTONE = object() class _KeyHistory: """Sparse version log for a single key using parallel lists for binary search.""" def __init__(self) -> None: # snap_ids: strictly increasing snapshot IDs, e.g. [0, 3, 5] self.snap_ids: List[int] = [] # values: matching int or _TOMBSTONE at each index, e.g. [15, _TOMBSTONE, 42] self.values: List[object] = [] class SnapshotMap: def __init__(self) -> None: # ID of the open, mutable window; frozen snapshots are 0 .. _active_snap_id - 1 self._active_snap_id: int = 0 # Maps each key that was ever set to its _KeyHistory self._histories: Dict[str, _KeyHistory] = {} def _record_change(self, key: str, value: object) -> None: """Write or coalesce a value/tombstone in the current active snapshot window.""" history = self._histories.get(key) if history is None: history = _KeyHistory() self._histories[key] = history if history.snap_ids and history.snap_ids[-1] == self._active_snap_id: # Write coalescing: key was already modified in this window, so overwrite # in place rather than appending a second entry for the same snap_id. history.values[-1] = value else: # _active_snap_id only increases, so appending keeps snap_ids sorted. history.snap_ids.append(self._active_snap_id) history.values.append(value) def put(self, key: str, val: int) -> None: self._record_change(key, val) def get(self, key: str) -> Optional[int]: history = self._histories.get(key) if history is None: return None latest_value = history.values[-1] if latest_value is _TOMBSTONE: return None return latest_value # type: ignore[return-value] def delete(self, key: str) -> None: # If the key was never set, or its latest entry is already a tombstone, # skip writing so repeated deletes do not bloat history. if self.get(key) is None: return self._record_change(key, _TOMBSTONE) def take_snapshot(self) -> int: frozen_id = self._active_snap_id self._active_snap_id += 1 return frozen_id def get_snapshot(self, key: str, snap_id: int) -> Optional[int]: # Reject negative IDs and the active (unfrozen) or future snapshot IDs. if snap_id < 0 or snap_id >= self._active_snap_id: raise ValueError( f"Invalid snap_id {snap_id}; frozen snapshot IDs are 0..{self._active_snap_id - 1}" ) history = self._histories.get(key) if history is None: return None # bisect_right returns the count of entries with recorded_id <= snap_id, # so subtracting 1 lands on the latest entry written at or before snap_id. idx = bisect_right(history.snap_ids, snap_id) - 1 if idx < 0: # Every recorded entry for this key happened after snap_id. return None recorded_value = history.values[idx] if recorded_value is _TOMBSTONE: return None return recorded_value # type: ignore[return-value] def history_size(self, key: str) -> int: history = self._histories.get(key) if history is None: return 0 return len(history.snap_ids)✅ Submit now — all tests should pass.
Intuition & how it works
Think of SnapshotMap like tracking price tags in a grocery store across numbered days. Instead of photographing every single shelf in the building each night, you attach a tiny dated price-change slip to an item only when its price actually changes (Day 0: 15, Day 3: discontinued). Closing out the day (take_snapshot()) simply flips the calendar number on the wall from Day 0 to Day 1 in instant O(1) time. When someone asks what milk cost on Day 2, you glance at milk's slip and find the last entry dated on or before Day 2.
The naive alternative — cloning the entire dictionary inside take_snapshot() — fails both scalability goals. Copying K keys takes O(K) time per snapshot instead of O(1), and S snapshots consume O(K * S) memory duplicating keys that never changed. Without write coalescing (merging repeated edits to the same key within the same open snapshot window into a single entry), rapid updates inside one window would also bloat memory with intermediate values nobody can ever query.
Trace four operations across "cpu" and "mem":
1. Window 0 starts open (_active_snap_id = 0). Calling put("cpu", 40), put("mem", 75), and put("cpu", 55) sees both "cpu" writes share window 0, so the second overwrites the first in place: "cpu" has snap_ids = [0], values = [55] and "mem" has snap_ids = [0], values = [75].
2. take_snapshot() freezes window 0, increments _active_snap_id to 1, and returns 0.
3. delete("mem") cannot erase "mem"'s history (snapshot 0 still needs 75), so it appends a tombstone (a special marker object _TOMBSTONE meaning "deleted as of this snapshot"): "mem" now has snap_ids = [0, 1], values = [75, _TOMBSTONE], followed by take_snapshot() returning 1.
4. get_snapshot("mem", 0) uses binary search (halving the sorted snap_ids list each step via bisect_right) to find the last ID <= 0 (index 0, returning 75), while get_snapshot("mem", 1) lands on index 1 (_TOMBSTONE, returning None).
Complexity
take_snapshot:O(1)time andO(1)extra space. We only read and increment the integer counter_active_snap_idwithout touching any keys.putanddelete:O(1)amortized average time. We do oneO(1)average hash-table lookup forkey, then either overwrite the last list slot inO(1)or append to a Python dynamic array in amortizedO(1)time (occasional list resizing spreads out to constant cost per append).get:O(1)average time. We look upkeyin_historiesinO(1)average time and inspecthistory.values[-1]inO(1).get_snapshot:O(log H_k)time. After anO(1)hash-table lookup forkey,bisect_rightbinary-searches theH_ksorted snapshot IDs recorded forkey, cutting the search range in half at each comparison.- Space:
O(K + U)._historiesholds one_KeyHistorywrapper for each of theKkeys ever written, and the parallel lists across all keys storeUentries — at most one per unique(key, snap_id)window where a modification occurred.
Edge cases
- Querying an unfrozen, future, or negative
snap_id:snap_id < 0orsnap_id >= _active_snap_idraisesValueErrorimmediately so uncommitted writes in the open window can never be read as a frozen snapshot. - Key first written after
snap_id:bisect_right(history.snap_ids, snap_id) - 1evaluates to-1, cleanly returningNone. - Key deleted and later recreated:
valuesalternates[10, _TOMBSTONE, 25]across snapshots, and binary search resolves each snapshot to whichever state was active then. - Multiple writes and deletes in the same window (
put,delete,put): coalesced in place sohistory_size(key)grows by at most1per snapshot window. - Deleting an absent or already-deleted key:
self.get(key) is Noneshort-circuits as a no-op so repeateddeletecalls add zero tombstone entries. - Storing integer
0:0is a valid value; checkingrecorded_value is _TOMBSTONE(object identity with a sentinel object) avoids the classic truthiness bugif not recorded_value:.
Common mistakes
- Using
bisect_leftinstead ofbisect_right. Whensnap_idmatches an entry exactly (saysnap_ids = [0, 4]andsnap_id = 4),bisect_leftreturns1and subtracting1steps backward to index0, returning a stale version. - Appending on every
putwithout checkingsnap_ids[-1] == _active_snap_id. Breaks write coalescing and turns space complexity fromO(K + U)intoO(total_writes). - Deleting the key from
_historiesinsidedelete(). Destroys historical values needed by earlier frozen snapshots instead of recording a tombstone. - Allowing
get_snapshot(key, _active_snap_id). Exposes mutable, uncommitted data from the open window, allowing twoget_snapshotcalls with the samesnap_idto return different values. - Using
-1orFalseas the tombstone marker. Collides with legitimateintvalues a caller might pass toput(key, -1)orput(key, 0).
Alternative approaches
- Persistent hash-array mapped trie (HAMT / copy-on-write tree): sharing unchanged subtrees lets
take_snapshot()save a root pointer inO(1)whileget_snapshotwalks aboutlog_32(K)tree levels independent ofH_k, at the cost of allocating ~4–6 path-copied tree nodes on every uncoalesced write instead of appending one array slot. - Per-key balanced binary search tree (e.g., Java
TreeMap.floorEntry): sameO(log H_k)historical read, though tree nodes add pointer overhead andO(log H_k)write cost that parallel dynamic arrays avoid because snapshot IDs arrive in strictly increasing order.
Follow-up questions
- How could you add a
compact(min_keep_snap)operation that frees historical versions predatingmin_keep_snapwithout corrupting reads at or after that cutoff? Trackself._min_snap_id = 0and rejectget_snapshotcalls withsnap_id < self._min_snap_id. Insidecompact(min_keep_snap), for each key findidx = bisect_right(history.snap_ids, min_keep_snap) - 1: entryidxis the exact version visible atmin_keep_snap, so slice away everything strictly older (del history.snap_ids[:idx]anddel history.values[:idx]). If the remaining front entry sits at<= min_keep_snapand is_TOMBSTONE, drop it too (since "no entry at or befores" also reads asNoneuntil the nextput), delete keys whose history becomes empty, and advanceself._min_snap_id = min_keep_snap. - If historical lookups had to avoid the
O(log H_k)per-key search, what trade-offs would a persistent copy-on-write tree introduce for writes and memory? StrictO(1)historical reads for arbitrary(key, snap_id)would require a denseK x Stable, violating the sparse-memory rule, whereas a persistent copy-on-write trie (HAMT) givesO(log_32 K)reads (roughly 4–5 pointer hops for a million keys — effectively constant regardless of how many thousands of times a hot key changed). The trade-off lands on writes and memory: every write in a HAMT allocates a path of new internal nodes (O(log_32 K)time and space per modified key), while per-key sorted arrays keepputandgetat trueO(1)with minimal memory and payO(log H_k)only on historical lookups. - How would you support concurrent read and write threads while keeping
take_snapshot()lock-free and wait-free? Make_active_snap_idan atomic integer sotake_snapshot()is a single lock-freefetch_and_add(1). Protect individual keys with lock striping (a fixed array of locks hashed bykey) and track an atomicin_flight_writers[epoch]counter: a writer acquires its key stripe lock, readss = _active_snap_id, incrementsin_flight_writers[s](retrying if_active_snap_idalready advanced), updates the key's history, and decrementsin_flight_writers[s].take_snapshot()never blocks; only aget_snapshot(..., s)called microseconds aftertake_snapshot()briefly spins or waits ifin_flight_writers[s] > 0, and once sealed, entries withrecorded_id <= sare immutable forever.
Follow-up questions
- How could you add a `compact(min_keep_snap)` operation that frees historical versions predating `min_keep_snap` without corrupting reads at or after that cutoff?
- If historical lookups had to avoid the `O(log H_k)` per-key search, what trade-offs would a persistent copy-on-write tree introduce for writes and memory?
- How would you support concurrent read and write threads while keeping `take_snapshot()` lock-free and wait-free?
Similar questions
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager
- Transactional Shopping Cart with Nested Scopes