Snapshot Queries on a Versioned Array

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Implement a snapshot-capable integer sequence of fixed capacity length (indices 0 through length - 1), exposed through the driver function:

def query_versioned_array(
    length: int,
    operations: List[str],
    arguments: List[List[int]],
) -> List[Optional[int]]:

Every slot begins holding 0 at snapshot 0. You are given parallel command lists operations and arguments, where step i executes one of two commands:

  • "set" with [index, value, version]: assign value to slot index starting at snapshot version and append None to the output list. Across all "set" commands, version timestamps are monotonically non-decreasing (v_1 <= v_2 <= ...). If the same index receives more than one "set" at the exact same version, the latest write supersedes earlier ones at that version.
  • "get" with [index, version]: look up and append the integer held by slot index at snapshot version. Specifically, return the value from the latest "set" on index whose write version satisfies write_version <= version, or 0 if no such write exists.

Each "get" lookup must execute in sub-linear time with respect to the number of prior writes, and memory usage should scale with the number of writes rather than length so sparse arrays remain fast.

Examples

Example 1

Input:
  length     = 4
  operations = ["set", "set", "get", "get", "get"]
  arguments  = [[2, 15, 1], [2, 30, 4], [2, 3], [2, 4], [2, 0]]

Output:
  [None, None, 15, 30, 0]

Walk-through: Slot 2 becomes 15 at snapshot 1 and 30 at snapshot 4. Querying slot 2 at snapshot 3 sees the snapshot-1 write (15), querying at snapshot 4 sees 30, and querying at snapshot 0 predates both writes so it returns the initial 0.

Example 2

Input:
  length     = 6
  operations = ["get", "set", "get", "set", "get", "get"]
  arguments  = [[1, 8], [1, -12, 4], [1, 2], [5, 25, 4], [5, 6], [3, 50]]

Output:
  [0, None, 0, None, 25, 0]

Walk-through: Before any writes, slot 1 reads 0. After setting slot 1 to -12 at snapshot 4, querying slot 1 at snapshot 2 still returns 0 because 2 < 4. Slot 5 becomes 25 at snapshot 4 (and reads 25 at snapshot 6), while untouched slot 3 always reads 0.

Example 3

Input:
  length     = 3
  operations = ["set", "set", "set", "get", "get", "get"]
  arguments  = [[0, 6, 3], [0, 14, 3], [0, 50, 7], [0, 3], [0, 9], [2, 40]]

Output:
  [None, None, None, 14, 50, 0]

Walk-through: Slot 0 is written twice at snapshot 3 (6, then 14), so 14 overwrites 6. A third write sets slot 0 to 50 at snapshot 7. Reading slot 0 at snapshot 3 returns 14, reading at snapshot 9 returns 50, and untouched slot 2 returns 0.

Constraints

  • 1 <= length <= 10^9
  • 0 <= len(operations) == len(arguments) <= 10^5
  • 0 <= index < length
  • version >= 0 is an integer, and "set" versions arrive in non-decreasing order.
  • Stored value entries may be negative, zero, or positive integers.

Step-by-step walkthrough

  1. Understand the versioned array rules

    We want to implement VersionedArray(length), modeling length integer slots (0 <= index < length) that all begin at 0 as of snapshot 0:

    • set(index, value, version) writes value into slot index effective at version. Across set calls, version timestamps never decrease (v_1 <= v_2 <= ...). If the same index is written multiple times at the same version, the latest write replaces earlier ones at that version.
    • get(index, version) asks: "what integer was stored at index as of version?" When no write happened right at version, the slot retains whatever value came from its latest write at or before version (or 0 if no write occurred at or before version).
    Timeline for slot 2 after set(2, 15, v=1) and set(2, 30, v=4):
    
    version:   0     1     2     3     4     5   ...
    value:     0    15    15    15    30    30   ...
               \_/  \____________/    \________
            init 0   from v=1 write   from v=4 write
    

    The driver query_versioned_array(length, operations, arguments) appends None for each "set" and the integer result for each "get".

  2. Why full array copies and flat update logs fall short

    Two naive designs break down once length or the write count U grows large:

    • Duplicate the entire length-N list on every snapshot: get is O(1), but every new snapshot allocates N integers. At N = 10,000,000 across thousands of snapshots, memory overflows immediately.
    • Append (index, value, version) to one flat log and scan it per get: memory stays O(U), but every get inspects up to U writes in O(U) time — failing the sub-linear lookup requirement.

    Instead of copying untouched slots or scanning unrelated slots, we can organize writes per slot.

  3. Key idea: a sparse dictionary of per-slot sorted histories

    Maintain a dictionary self.history mapping only touched indices to their own chronologically ordered [version, value] lists:

    1. Sparse memory (O(U)): Even if length = 10,000,000 and only 3 slots ever change, self.history holds just 3 keys. Any slot absent from self.history still reads 0 at every version.
    2. Naturally ordered writes: Because set versions arrive in non-decreasing order, each incoming version for index is >= the tail entry cell_history[-1][0].
    3. In-place overwrite on equal versions (O(1)): When cell_history[-1][0] == version, we overwrite cell_history[-1][1] = value in place so the last write wins and recorded versions remain strictly increasing. Otherwise we append([version, value]).
    4. Logarithmic get via binary search: Because cell_history has strictly increasing versions, locating the rightmost entry with update_version <= version runs in O(log k) time (for k snapshots stored at that index).
  4. Implement storage and O(1) `set`

    We save self.length for bounds validation and self.history for per-slot [version, value] lists.

    class VersionedArray:
        def __init__(self, length: int) -> None:
            self.length = length
            # history: maps each updated index -> strictly increasing list of [version, value] pairs.
            # Example: self.history[0] = [[3, 14], [7, 50]] means index 0 became 14 at v3 and 50 at v7.
            # Untouched indices are omitted so memory stays O(updates) even when `length` is huge.
            self.history: Dict[int, List[List[int]]] = {}
    
        def _validate_index(self, index: int) -> None:
            if not (0 <= index < self.length):
                raise IndexError(f"Index {index} out of bounds for length {self.length}")
    
        def set(self, index: int, value: int, version: int) -> None:
            self._validate_index(index)
            if index not in self.history:
                self.history[index] = []
    
            cell_history = self.history[index]
            # Multiple updates to the same index at the same version: last write wins in place.
            if cell_history and cell_history[-1][0] == version:
                cell_history[-1][1] = value
            else:
                # Update versions are non-decreasing, so appending keeps cell_history sorted.
                cell_history.append([version, value])
    
  5. Find the right snapshot with binary search in `get`

    When get(index, version) searches cell_history, we want the rightmost pair [mid_version, mid_value] satisfying mid_version <= version (defaulting to best_value = 0 if every recorded write occurred strictly after version):

    • If mid_version <= version, this write was already in effect at version! Record best_value = mid_value, and advance left = mid + 1 to look for a still-newer qualifying write to the right.
    • If mid_version > version, this write happened after our target snapshot; discard it and move right = mid - 1 to inspect older writes on the left.
    Query get(index=2, version=3) on cell_history = [[1, 15], [4, 30], [9, 45]]:
    
    Step 1: left=0, right=2 -> mid=1 -> [4, 30]: 4 > 3 (too new!) -> right = 0
    Step 2: left=0, right=0 -> mid=0 -> [1, 15]: 1 <= 3 (valid!)  -> best_value = 15, left = 1
    Loop ends (left > right) -> return best_value = 15
    

    Here is get:

        def get(self, index: int, version: int) -> int:
            self._validate_index(index)
            # Never-updated indices stay at their initial value 0 across all versions.
            if index not in self.history:
                return 0
    
            cell_history = self.history[index]
            # Binary search for the rightmost (latest) update with update_version <= version.
            left = 0
            right = len(cell_history) - 1
            best_value = 0  # Fallback to initial 0 if every recorded update happened after `version`
    
            while left <= right:
                mid = (left + right) // 2
                mid_version, mid_value = cell_history[mid]
                if mid_version <= version:
                    # Valid snapshot at or before `version`; save it and search right for a newer one.
                    best_value = mid_value
                    left = mid + 1
                else:
                    # Update happened after `version`; search left for an older one.
                    right = mid - 1
    
            return best_value
    
  6. Dispatch operations and trace Example 3

    The driver query_versioned_array creates VersionedArray(length) and runs each command in sequence.

    def query_versioned_array(length: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
        array = VersionedArray(length)
        results: List[Optional[int]] = []
    
        # Execute each operation in sequence; `set` returns None and `get` returns the queried value.
        for op, args in zip(operations, arguments):
            if op == "set":
                array.set(args[0], args[1], args[2])
                results.append(None)
            elif op == "get":
                results.append(array.get(args[0], args[1]))
            else:
                raise ValueError(f"Unknown operation: {op}")
    
        return results
    

    Let's trace Example 3 (length = 3):

    1. set(0, 6, 3)   -> history[0] = [[3, 6]]                     output: None
    2. set(0, 14, 3)  -> same version 3! overwrite in place:
                         history[0] = [[3, 14]]                    output: None
    3. set(0, 50, 7)  -> version 7 > 3, append:
                         history[0] = [[3, 14], [7, 50]]           output: None
    4. get(0, 3)      -> rightmost version <= 3 is [3, 14]         output: 14
    5. get(0, 9)      -> rightmost version <= 9 is [7, 50]         output: 50
    6. get(2, 40)     -> slot 2 not in history -> initial default  output: 0
    

    The returned list is [None, None, None, 14, 50, 0].

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    class VersionedArray:
        def __init__(self, length: int) -> None:
            self.length = length
            # history: maps each updated index -> strictly increasing list of [version, value] pairs.
            # Example: self.history[0] = [[3, 14], [7, 50]] means index 0 became 14 at v3 and 50 at v7.
            # Untouched indices are omitted so memory stays O(updates) even when `length` is huge.
            self.history: Dict[int, List[List[int]]] = {}
    
        def _validate_index(self, index: int) -> None:
            if not (0 <= index < self.length):
                raise IndexError(f"Index {index} out of bounds for length {self.length}")
    
        def set(self, index: int, value: int, version: int) -> None:
            self._validate_index(index)
            if index not in self.history:
                self.history[index] = []
    
            cell_history = self.history[index]
            # Multiple updates to the same index at the same version: last write wins in place.
            if cell_history and cell_history[-1][0] == version:
                cell_history[-1][1] = value
            else:
                # Update versions are non-decreasing, so appending keeps cell_history sorted.
                cell_history.append([version, value])
    
        def get(self, index: int, version: int) -> int:
            self._validate_index(index)
            # Never-updated indices stay at their initial value 0 across all versions.
            if index not in self.history:
                return 0
    
            cell_history = self.history[index]
            # Binary search for the rightmost (latest) update with update_version <= version.
            left = 0
            right = len(cell_history) - 1
            best_value = 0  # Fallback to initial 0 if every recorded update happened after `version`
    
            while left <= right:
                mid = (left + right) // 2
                mid_version, mid_value = cell_history[mid]
                if mid_version <= version:
                    # Valid snapshot at or before `version`; save it and search right for a newer one.
                    best_value = mid_value
                    left = mid + 1
                else:
                    # Update happened after `version`; search left for an older one.
                    right = mid - 1
    
            return best_value
    
    
    def query_versioned_array(length: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
        array = VersionedArray(length)
        results: List[Optional[int]] = []
    
        # Execute each operation in sequence; `set` returns None and `get` returns the queried value.
        for op, args in zip(operations, arguments):
            if op == "set":
                array.set(args[0], args[1], args[2])
                results.append(None)
            elif op == "get":
                results.append(array.get(args[0], args[1]))
            else:
                raise ValueError(f"Unknown operation: {op}")
    
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine every array slot keeping its own price-change ledger in a shop: instead of reprinting an entire store-wide catalog whenever a single product's price changes, you simply append [day, new_price] to that one product's card. Because writes arrive in non-decreasing version order, every card's timestamps stay naturally sorted! When a query asks for a slot's value at snapshot v, you run binary search — repeatedly halving the sorted card by checking its middle entry — to jump straight to the newest entry stamped <= v (falling back to 0 if no entry is that old). Keeping these cards inside a sparse dictionary (creating entries only for indices that receive writes) means untouched slots take zero memory.

Both naive alternatives blow up on either space or query latency. Cloning the whole length-N array on each snapshot spends O(N) time and memory per snapshot, which fails immediately when N = 10^9 and only a few slots change. Meanwhile, pushing every (index, value, version) triple into one shared list and scanning it linearly on each get costs O(U) time per query across U writes, violating the sub-linear read target when tens of thousands of reads follow tens of thousands of writes.

Walk through Example 1 with length = 4:

  1. set(2, 15, 1) creates ledger history[2] = [[1, 15]].
  2. set(2, 30, 4) sees version 4 > 1 and appends [[1, 15], [4, 30]]. (If another set(2, 99, 4) arrived at version 4, it would overwrite [4, 30] to [4, 99] in place.)
  3. get(2, 3) binary-searches [[1, 15], [4, 30]] for the rightmost version <= 3, landing on [1, 15] -> returns 15.
  4. get(2, 0) finds every recorded version (1, 4) is > 0, so it keeps the fallback best_value = 0 -> returns 0.
  5. get(3, 4) sees slot 3 has no key in history -> immediately returns 0.

Complexity

Let N be the array length, U be the total number of set calls, and k be the number of distinct versions recorded for the queried index (k <= U).

  • __init__ time — O(1): Stores length and an empty dictionary without allocating an O(N) buffer.
  • set time — O(1) amortized: Performs an O(1) hash-map lookup on index and either overwrites the tail pair in O(1) or appends to the dynamic list in amortized O(1) time (occasional list resizes average out to constant cost per append).
  • get time — O(log k): Checks self.history in O(1), then halves the k-entry sorted history on each step of binary search in at most floor(log2(k)) + 1 iterations (O(log U) worst case if all writes target one slot).
  • Space — O(U): Every set adds at most one [version, value] pair, while untouched slots consume zero memory regardless of N.

Edge cases

  • Slot never written: index not in self.history returns 0 immediately for any queried snapshot (0 or 10^9).
  • Query version earlier than the first write: When history[1] = [[4, -12]] and we call get(1, 2) or get(1, 0), every mid_version > version, so best_value stays 0.
  • Query version between or past recorded writes: get(2, 3) on [[1, 15], [4, 30]] returns 15 (from snapshot 1), and get(2, 100) returns 30 (from snapshot 4).
  • Repeated set calls at the same (index, version): cell_history[-1][0] == version overwrites cell_history[-1][1] in place so the last write wins even if a get ran in between.
  • Explicit write at version = 0: set(0, 7, 0) stores [0, 7], replacing the initial 0 for get(0, 0) and higher versions.
  • Writing 0 after a non-zero value: set(0, -5, 1) followed by set(0, 0, 2) stores [[1, -5], [2, 0]]; tracking best_value explicitly ensures get(0, 3) returns 0 rather than -5.

Common mistakes

  • Using bisect_left instead of bisect_right (missing exact version hits): With library binary search, bisect_left([1, 4], 1) returns index 0, and subtracting 1 steps before index 0 — missing the write at snapshot 1! Always include equality (<=, or bisect_right(...) - 1).
  • Appending duplicate versions and stopping on the first hit: If two writes at snapshot 3 leave [[3, 6], [3, 14]], stopping as soon as mid_version == 3 can return the stale 6 instead of 14. Overwriting in place keeps versions strictly increasing.
  • Allocating [[] for _ in range(length)] up front: Spends O(N) time and memory during initialization, timing out when length is 10^7 or 10^9 with sparse writes.
  • Treating 0 as falsy ("missing"): Writing return value or previous_value fails whenever a caller resets a slot back to 0.
  • Appending blindly if versions could arrive out of order: Here non-decreasing set versions are guaranteed; without that guarantee, unsorted appends would corrupt binary search.

Alternative approaches

  • Parallel version/value lists with bisect.bisect_right: Maintain self.versions[index] and self.values[index] as separate lists and compute pos = bisect.bisect_right(self.versions[index], version). Return 0 when pos == 0, else self.values[index][pos - 1]. Same O(1) set, O(log k) get, and O(U) memory using C-accelerated bisect.
  • Persistent segment tree (path copying): A persistent segment tree is a balanced binary tree over [0, N - 1] where each write clones only the O(log N) nodes on the root-to-leaf path while sharing unmodified subtrees. It uses O(U log N) memory and O(log U + log N) lookup time — unnecessary for point lookups, but ideal if you also need historical range queries like range_sum(left, right, version).

Follow-up questions

  • How can we keep memory usage proportional to the number of writes when most array slots are never touched? Storing per-slot histories in a hash map self.history rather than a pre-allocated length-N list already achieves optimal O(U) space: untouched indices have no dictionary entry and default to 0, so length = 10^9 with 50 writes allocates at most 50 entries. Merging same-version writes in place (cell_history[-1][1] = value) further bounds memory by the count of distinct (index, version) pairs. Conversely, if N is small and nearly dense, a fixed array of N lists avoids hash-map overhead.
  • What are the asymptotic runtime and memory costs of set and get in this approach? set(index, value, version) runs in O(1) amortized time: after an O(1) dictionary lookup, non-decreasing versions allow either an O(1) tail overwrite or an amortized O(1) list append. get(index, version) runs in O(log k) time and O(1) auxiliary space, where k is the number of distinct snapshots written to index (O(log U) worst case), via binary search on self.history[index]. Total memory across the whole structure is O(U) for U writes, independent of length.
  • How would you extend the data structure to support rolling back or removing a specific snapshot via delete_version(version)? Interpreting delete_version(v) as "discard all writes recorded at snapshot v so queries fall back to the latest surviving write prior to v", add a reverse index self.changed_at: Dict[int, Set[int]] tracking which slots were modified at each version so we never scan every key in self.history. On delete_version(v), pop self.changed_at[v] and binary-search each affected self.history[index] to remove [v, value]: rolling back the latest version pops from the tail in O(1) per affected slot, while frequent arbitrary mid-history deletions can use a balanced BST per slot to avoid O(k) list shifts:
# Add to __init__: self.changed_at: Dict[int, Set[int]] = {}
# Add to set:      self.changed_at.setdefault(version, set()).add(index)

def delete_version(self, version: int) -> None:
    for index in self.changed_at.pop(version, set()):
        cell_history = self.history[index]
        left, right = 0, len(cell_history) - 1
        while left <= right:
            mid = (left + right) // 2
            if cell_history[mid][0] == version:
                cell_history.pop(mid)
                break
            elif cell_history[mid][0] < version:
                left = mid + 1
            else:
                right = mid - 1
        if not cell_history:
            del self.history[index]

Follow-up questions

Similar questions

More Truefoundry interview questions

All 3 Truefoundry questions →