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]: assignvalueto slotindexstarting at snapshotversionand appendNoneto the output list. Across all"set"commands,versiontimestamps are monotonically non-decreasing (v_1 <= v_2 <= ...). If the sameindexreceives more than one"set"at the exact sameversion, the latest write supersedes earlier ones at thatversion."get"with[index, version]: look up and append the integer held by slotindexat snapshotversion. Specifically, return the value from the latest"set"onindexwhose write version satisfieswrite_version <= version, or0if 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^90 <= len(operations) == len(arguments) <= 10^50 <= index < lengthversion >= 0is an integer, and"set"versions arrive in non-decreasing order.- Stored
valueentries may be negative, zero, or positive integers.
Step-by-step walkthrough
Understand the versioned array rules
We want to implement
VersionedArray(length), modelinglengthinteger slots (0 <= index < length) that all begin at0as of snapshot0:set(index, value, version)writesvalueinto slotindexeffective atversion. Acrosssetcalls,versiontimestamps never decrease (v_1 <= v_2 <= ...). If the sameindexis written multiple times at the sameversion, the latest write replaces earlier ones at thatversion.get(index, version)asks: "what integer was stored atindexas ofversion?" When no write happened right atversion, the slot retains whatever value came from its latest write at or beforeversion(or0if no write occurred at or beforeversion).
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 writeThe driver
query_versioned_array(length, operations, arguments)appendsNonefor each"set"and the integer result for each"get".Why full array copies and flat update logs fall short
Two naive designs break down once
lengthor the write countUgrows large:- Duplicate the entire length-
Nlist on every snapshot:getisO(1), but every new snapshot allocatesNintegers. AtN = 10,000,000across thousands of snapshots, memory overflows immediately. - Append
(index, value, version)to one flat log and scan it perget: memory staysO(U), but everygetinspects up toUwrites inO(U)time — failing the sub-linear lookup requirement.
Instead of copying untouched slots or scanning unrelated slots, we can organize writes per slot.
- Duplicate the entire length-
Key idea: a sparse dictionary of per-slot sorted histories
Maintain a dictionary
self.historymapping only touched indices to their own chronologically ordered[version, value]lists:- Sparse memory (
O(U)): Even iflength = 10,000,000and only 3 slots ever change,self.historyholds just 3 keys. Any slot absent fromself.historystill reads0at every version. - Naturally ordered writes: Because
setversions arrive in non-decreasing order, each incomingversionforindexis>=the tail entrycell_history[-1][0]. - In-place overwrite on equal versions (
O(1)): Whencell_history[-1][0] == version, we overwritecell_history[-1][1] = valuein place so the last write wins and recorded versions remain strictly increasing. Otherwise weappend([version, value]). - Logarithmic
getvia binary search: Becausecell_historyhas strictly increasing versions, locating the rightmost entry withupdate_version <= versionruns inO(log k)time (forksnapshots stored at thatindex).
- Sparse memory (
Implement storage and O(1) `set`
We save
self.lengthfor bounds validation andself.historyfor 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])Find the right snapshot with binary search in `get`
When
get(index, version)searchescell_history, we want the rightmost pair[mid_version, mid_value]satisfyingmid_version <= version(defaulting tobest_value = 0if every recorded write occurred strictly afterversion):- If
mid_version <= version, this write was already in effect atversion! Recordbest_value = mid_value, and advanceleft = mid + 1to look for a still-newer qualifying write to the right. - If
mid_version > version, this write happened after our target snapshot; discard it and moveright = mid - 1to 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 = 15Here 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- If
Dispatch operations and trace Example 3
The driver
query_versioned_arraycreatesVersionedArray(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 resultsLet'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: 0The returned list is
[None, None, None, 14, 50, 0].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:
set(2, 15, 1)creates ledgerhistory[2] = [[1, 15]].set(2, 30, 4)sees version4 > 1and appends[[1, 15], [4, 30]]. (If anotherset(2, 99, 4)arrived at version4, it would overwrite[4, 30]to[4, 99]in place.)get(2, 3)binary-searches[[1, 15], [4, 30]]for the rightmost version<= 3, landing on[1, 15]-> returns15.get(2, 0)finds every recorded version (1,4) is> 0, so it keeps the fallbackbest_value = 0-> returns0.get(3, 4)sees slot3has no key inhistory-> immediately returns0.
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): Storeslengthand an empty dictionary without allocating an O(N) buffer.settime — O(1) amortized: Performs an O(1) hash-map lookup onindexand 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).gettime — O(log k): Checksself.historyin O(1), then halves thek-entry sorted history on each step of binary search in at mostfloor(log2(k)) + 1iterations (O(log U)worst case if all writes target one slot).- Space — O(U): Every
setadds at most one[version, value]pair, while untouched slots consume zero memory regardless of N.
Edge cases
- Slot never written:
index not in self.historyreturns0immediately for any queried snapshot (0or10^9). - Query version earlier than the first write: When
history[1] = [[4, -12]]and we callget(1, 2)orget(1, 0), everymid_version > version, sobest_valuestays0. - Query version between or past recorded writes:
get(2, 3)on[[1, 15], [4, 30]]returns15(from snapshot1), andget(2, 100)returns30(from snapshot4). - Repeated
setcalls at the same(index, version):cell_history[-1][0] == versionoverwritescell_history[-1][1]in place so the last write wins even if agetran in between. - Explicit write at
version = 0:set(0, 7, 0)stores[0, 7], replacing the initial0forget(0, 0)and higher versions. - Writing
0after a non-zero value:set(0, -5, 1)followed byset(0, 0, 2)stores[[1, -5], [2, 0]]; trackingbest_valueexplicitly ensuresget(0, 3)returns0rather than-5.
Common mistakes
- Using
bisect_leftinstead ofbisect_right(missing exact version hits): With library binary search,bisect_left([1, 4], 1)returns index0, and subtracting1steps before index0— missing the write at snapshot1! Always include equality (<=, orbisect_right(...) - 1). - Appending duplicate versions and stopping on the first hit: If two writes at snapshot
3leave[[3, 6], [3, 14]], stopping as soon asmid_version == 3can return the stale6instead of14. Overwriting in place keeps versions strictly increasing. - Allocating
[[] for _ in range(length)]up front: Spends O(N) time and memory during initialization, timing out whenlengthis10^7or10^9with sparse writes. - Treating
0as falsy ("missing"): Writingreturn value or previous_valuefails whenever a caller resets a slot back to0. - Appending blindly if versions could arrive out of order: Here non-decreasing
setversions are guaranteed; without that guarantee, unsorted appends would corrupt binary search.
Alternative approaches
- Parallel version/value lists with
bisect.bisect_right: Maintainself.versions[index]andself.values[index]as separate lists and computepos = bisect.bisect_right(self.versions[index], version). Return0whenpos == 0, elseself.values[index][pos - 1]. Same O(1)set, O(log k)get, and O(U) memory using C-acceleratedbisect. - 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 likerange_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.historyrather than a pre-allocated length-Nlist already achieves optimal O(U) space: untouched indices have no dictionary entry and default to0, solength = 10^9with 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, ifNis small and nearly dense, a fixed array ofNlists avoids hash-map overhead. - What are the asymptotic runtime and memory costs of
setandgetin 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, wherekis the number of distinct snapshots written toindex(O(log U)worst case), via binary search onself.history[index]. Total memory across the whole structure is O(U) forUwrites, independent oflength. - How would you extend the data structure to support rolling back or removing a specific snapshot via
delete_version(version)? Interpretingdelete_version(v)as "discard all writes recorded at snapshotvso queries fall back to the latest surviving write prior tov", add a reverse indexself.changed_at: Dict[int, Set[int]]tracking which slots were modified at each version so we never scan every key inself.history. Ondelete_version(v), popself.changed_at[v]and binary-search each affectedself.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
- How can we keep memory usage proportional to the number of writes when most array slots are never touched?
- What are the asymptotic runtime and memory costs of `set` and `get` in this approach?
- How would you extend the data structure to support rolling back or removing a specific snapshot via `delete_version(version)`?
Similar questions
- Check Lexicographical Order With Custom Alphabet
- Concurrent Interview Scheduling and Availability API
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance