Time-Travel Array with Historical Query Support
Data Structure DesignAuto-graded · 21 test casesLast updated
Design a data structure that tracks an array's evolution through snapshots and answers queries about past states efficiently.
Implement a time-traveling integer array that maintains a complete history through snapshots. The array has a fixed size and all elements begin at zero. You'll process three types of operations: modifying values in the current state, capturing snapshots, and retrieving values from previous snapshots.
Your task is to process a sequence of operations and return the results of snapshot and query operations.
Function Signature
def process_versioned_array(size: int, operations: List[str], parameters: List[List[int]]) -> List[int]:
Operation Types
The operations and parameters lists describe the sequence of commands to execute:
-
"set" with
parameters[i] = [index, value]: Update the element at positionindextovaluein the current array state. Produces no output. -
"snap" with
parameters[i] = []: Create a numbered snapshot of the current array state and return the snapshot identifier. Snapshot IDs start at 0 and increment by 1 each time a snapshot is created. -
"get" with
parameters[i] = [index, snap_id]: Return the value stored at positionindexwhen snapshotsnap_idwas created.
Behavior Rules
- Snapshots capture the array state at the moment they are created, including all preceding "set" operations but excluding any subsequent ones.
- If a position is modified multiple times between consecutive snapshots, only the most recent value appears in the next snapshot.
- Any array position that has never been set reads as 0 in all snapshots.
- Return a list containing all outputs from "snap" and "get" operations, in the order they occur.
Constraints
1 <= size <= 5 * 10^41 <= len(operations) == len(parameters) <= 5 * 10^4- Each
operations[i]is either"set","snap", or"get" - For "set" operations:
0 <= index < sizeand0 <= value <= 10^9 - For "get" operations:
0 <= index < sizeand0 <= snap_id < total_snapshots, wheretotal_snapshotsis the count of "snap" operations before this "get"
Examples
Example 1
Input: process_versioned_array(3, ['set', 'snap', 'set', 'get'], [[0, 5], [], [0, 6], [0, 0]])
Output: [0, 5]
Example 2
Input: process_versioned_array(2, ['snap', 'snap', 'get', 'set', 'get', 'snap', 'get', 'get'], [[], [], [1, 1], [1, 4], [1, 1], [], [1, 2], [0, 2]])
Output: [0, 1, 0, 0, 2, 4, 0]
Example 3
Input: process_versioned_array(1, ['set', 'set', 'snap', 'set', 'get'], [[0, 3], [0, 7], [], [0, 9], [0, 0]])
Output: [0, 7]
Hints
Hint 1
Storing a full array copy for each snapshot is too slow—think about what information actually changes between snapshots.
Hint 2
Track modifications on a per-index basis. Each array position can maintain its own history of changes tagged with version numbers.
Hint 3
When searching through a position's history for a specific snapshot, you need the most recent change that occurred at or before that snapshot—binary search can help.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The naive solution—duplicating the entire array on every snapshot—would require O(size × snapshots) space and time, which becomes prohibitively expensive when both dimensions reach their upper limits.
Instead, track only what changes. For each array position, maintain a chronological log of modifications as (version_number, value) pairs:
- Maintain a version counter that represents the ID the next snapshot will receive
- set operation: Record the change with the current version number. If this position was already modified during the current version, overwrite that entry since only the final value before a snapshot matters
- snap operation: Return the current version number and increment it
- get operation: Search the history for the target position to find the most recent entry whose version number doesn't exceed the requested snapshot ID
Each position's history begins with a sentinel entry (-1, 0) representing the initial zero state, ensuring queries always find a valid answer.
Correctness
Each history entry (v, val) records that "when snapshot v was taken, this position held val." Two properties guarantee correctness:
- One entry per version: The overwrite rule ensures at most one history entry exists for each version number, containing the final value written during that version
- Monotonically increasing versions: Since the version counter only increments, history entries are naturally sorted by version number
A snapshot with ID s captures all modifications from versions 0 through s. The value at any position equals the value from the highest version ≤ s where that position was modified. This is exactly what the binary search finds. If no modification occurred by version s, the sentinel correctly provides 0.
The binary search maintains lo pointing to an entry guaranteed to satisfy version <= s. Starting at index 0 (the sentinel with version -1) ensures this invariant. Using the upper-biased midpoint (lo + hi + 1) // 2 prevents infinite loops when lo == hi - 1.
Complexity
Let n be the number of operations.
- Time: O(size + n log n). Initialization creates
sizeempty histories. Each set is O(1). Each get performs binary search on a history of length at most n, giving O(log n). Snap is O(1). - Space: O(size + modifications), where modifications is the number of set operations. Each set adds at most one history entry due to the overwrite optimization.
Solution Code
from typing import List
def process_versioned_array(size: int, operations: List[str], parameters: List[List[int]]) -> List[int]:
# For each index, maintain a history of (version, value) pairs
# Start with (-1, 0) sentinel to handle unset positions
history = [[(-1, 0)] for _ in range(size)]
current_version = 0 # The version number for the next snapshot
results = []
for op, params in zip(operations, parameters):
if op == "set":
idx, val = params
h = history[idx]
# If we already have an entry for the current version, replace it
# Otherwise, append a new entry
if h[-1][0] == current_version:
h[-1] = (current_version, val)
else:
h.append((current_version, val))
elif op == "snap":
results.append(current_version)
current_version += 1
else: # "get"
idx, snap_id = params
h = history[idx]
# Binary search for the last entry with version <= snap_id
lo, hi = 0, len(h) - 1
while lo < hi:
mid = (lo + hi + 1) // 2
if h[mid][0] <= snap_id:
lo = mid
else:
hi = mid - 1
results.append(h[lo][1])
return results