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 ID 0.
  • put(key: str, val: int) -> None: Stores integer val under key in the currently open window, replacing any earlier uncommitted change to key in that same window.
  • get(key: str) -> Optional[int]: Returns the current value of key (including uncommitted edits in the open window), or None if key has never been written or is currently deleted.
  • delete(key: str) -> None: Marks key deleted in the open window using a tombstone marker. Calling delete on 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 by 1, and returns the ID that was just sealed (0, 1, 2, ...).
  • get_snapshot(key: str, snap_id: int) -> Optional[int]: Returns the value associated with key when snapshot snap_id was sealed, or None if key was absent or deleted then. Raises ValueError whenever snap_id < 0 or snap_id is 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 for key (0 if key was 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 in O(1) time.
  • put(key, val) and delete(key) must run in O(1) amortized average time.
  • get(key) and history_size(key) must run in O(1) average time.
  • get_snapshot(key, snap_id) must run in O(log H_k) time, where H_k = history_size(key).
  • Total memory usage must be O(K + U), where K is the number of distinct keys ever written and U is the number of distinct (key, snap_id) windows in which a state change was recorded.
  • Keys are arbitrary strings; val may be any integer, including 0 and negative values.

Step-by-step walkthrough

  1. Understand snapshot windows, sparse histories, and coalescing

    Think of time in SnapshotMap as 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 2
    
    • get(key) always reads the latest state, including uncommitted writes in the currently open window.
    • get_snapshot(key, snap_id) reads the frozen state as of snap_id (0 <= snap_id < _active_snap_id).
    • Sparse history: if "port" is set in window 0 and untouched across later snapshots, "port" still stores only one record until modified again.
    • Write coalescing: if "cpu" is written multiple times inside window 0, all writes in that window collapse into one record for window 0.
  2. Why copying the dictionary on every snapshot fails

    The obvious first try keeps a current dictionary and copies dict(current) into a list every time take_snapshot() is called. Historical reads are trivial (frozen[snap_id].get(key)), yet both core constraints break:

    • Snapshot time becomes O(K) instead of O(1), because copying 100,000 keys copies 100,000 entries even if nothing changed.
    • Space explodes to O(K * S) instead of O(K + U): 100,000 keys across 10,000 snapshots 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.

  3. Store parallel `(snap_ids, values)` lists and a tombstone object

    Why can't delete(key) simply delete key from our map? Because earlier frozen snapshots still need key'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 like 0 or -1 can never collide with it. For each key, _KeyHistory stores two parallel lists — snap_ids and values — so Python's bisect_right can binary-search snap_ids directly 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] = []
    
  4. Coalesce writes in place and freeze snapshots in O(1)

    Both put and delete funnel through one helper _record_change(key, value):

    1. Look up (or create) history = self._histories[key].
    2. 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 — overwrite history.values[-1] = value in place (coalescing).
      • Otherwise, append self._active_snap_id and value. Because self._active_snap_id only ever increments, history.snap_ids stays strictly increasing automatically!

    For delete(key), check if self.get(key) is None: return first. If the key has never been set, or its latest entry is already _TOMBSTONE, deleting it again changes nothing and writes no extra record. And take_snapshot() simply returns self._active_snap_id and adds 1 — pure O(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
    
  5. Query frozen snapshots with `bisect_right`

    Suppose key "k" changed in snapshots 1, 4, and 7, with values [10, 40, _TOMBSTONE], and _active_snap_id is 9. What was "k"'s value at snapshot snap_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 existing snap_id — which equals the count of recorded IDs <= snap_id. Subtracting 1 lands 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      -> None
    

    Notice why bisect_left would be a bug on snap_id = 4: bisect_left([1, 4, 7], 4) returns 1, and 1 - 1 = 0 would step backward to snapshot 1's stale value 10! Also notice why uncommitted writes in the open window (snap_id == _active_snap_id) never leak into frozen queries: get_snapshot rejects snap_id >= _active_snap_id up front, and for any snap_id < _active_snap_id, an uncommitted entry at _active_snap_id sits strictly to the right of bisect_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)
    
  6. 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 -> raises ValueError.
  7. 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 and O(1) extra space. We only read and increment the integer counter _active_snap_id without touching any keys.
  • put and delete: O(1) amortized average time. We do one O(1) average hash-table lookup for key, then either overwrite the last list slot in O(1) or append to a Python dynamic array in amortized O(1) time (occasional list resizing spreads out to constant cost per append).
  • get: O(1) average time. We look up key in _histories in O(1) average time and inspect history.values[-1] in O(1).
  • get_snapshot: O(log H_k) time. After an O(1) hash-table lookup for key, bisect_right binary-searches the H_k sorted snapshot IDs recorded for key, cutting the search range in half at each comparison.
  • Space: O(K + U). _histories holds one _KeyHistory wrapper for each of the K keys ever written, and the parallel lists across all keys store U entries — 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 < 0 or snap_id >= _active_snap_id raises ValueError immediately 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) - 1 evaluates to -1, cleanly returning None.
  • Key deleted and later recreated: values alternates [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 so history_size(key) grows by at most 1 per snapshot window.
  • Deleting an absent or already-deleted key: self.get(key) is None short-circuits as a no-op so repeated delete calls add zero tombstone entries.
  • Storing integer 0: 0 is a valid value; checking recorded_value is _TOMBSTONE (object identity with a sentinel object) avoids the classic truthiness bug if not recorded_value:.

Common mistakes

  • Using bisect_left instead of bisect_right. When snap_id matches an entry exactly (say snap_ids = [0, 4] and snap_id = 4), bisect_left returns 1 and subtracting 1 steps backward to index 0, returning a stale version.
  • Appending on every put without checking snap_ids[-1] == _active_snap_id. Breaks write coalescing and turns space complexity from O(K + U) into O(total_writes).
  • Deleting the key from _histories inside delete(). 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 two get_snapshot calls with the same snap_id to return different values.
  • Using -1 or False as the tombstone marker. Collides with legitimate int values a caller might pass to put(key, -1) or put(key, 0).

Alternative approaches

  • Persistent hash-array mapped trie (HAMT / copy-on-write tree): sharing unchanged subtrees lets take_snapshot() save a root pointer in O(1) while get_snapshot walks about log_32(K) tree levels independent of H_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): same O(log H_k) historical read, though tree nodes add pointer overhead and O(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 predating min_keep_snap without corrupting reads at or after that cutoff? Track self._min_snap_id = 0 and reject get_snapshot calls with snap_id < self._min_snap_id. Inside compact(min_keep_snap), for each key find idx = bisect_right(history.snap_ids, min_keep_snap) - 1: entry idx is the exact version visible at min_keep_snap, so slice away everything strictly older (del history.snap_ids[:idx] and del history.values[:idx]). If the remaining front entry sits at <= min_keep_snap and is _TOMBSTONE, drop it too (since "no entry at or before s" also reads as None until the next put), delete keys whose history becomes empty, and advance self._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? Strict O(1) historical reads for arbitrary (key, snap_id) would require a dense K x S table, violating the sparse-memory rule, whereas a persistent copy-on-write trie (HAMT) gives O(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 keep put and get at true O(1) with minimal memory and pay O(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_id an atomic integer so take_snapshot() is a single lock-free fetch_and_add(1). Protect individual keys with lock striping (a fixed array of locks hashed by key) and track an atomic in_flight_writers[epoch] counter: a writer acquires its key stripe lock, reads s = _active_snap_id, increments in_flight_writers[s] (retrying if _active_snap_id already advanced), updates the key's history, and decrements in_flight_writers[s]. take_snapshot() never blocks; only a get_snapshot(..., s) called microseconds after take_snapshot() briefly spins or waits if in_flight_writers[s] > 0, and once sealed, entries with recorded_id <= s are immutable forever.

Follow-up questions

Similar questions

More Snorkel interview questions

All 1 Snorkel questions →