Snapshot Array

Implement `SnapshotArray`, an array-like structure that can take snapshots. - `SnapshotArray(int length)` creates an array of the given length where every element starts as 0. - `void set(index, val)` sets the element at `index` to `val`. - `int snap()` takes a snapshot and returns its `snap_id`, which is the total number of times `snap()` has been called minus 1. - `int get(index, snap_id)` returns the value that `index` held when the snapshot `snap_id` was taken.

30:00

Snapshot Array
medium
Free written solution
Topics
Companies

Implement SnapshotArray, an array-like structure that can take snapshots.

  • SnapshotArray(int length) creates an array of the given length where every element starts as 0.
  • void set(index, val) sets the element at index to val.
  • int snap() takes a snapshot and returns its snap_id, which is the total number of times snap() has been called minus 1.
  • int get(index, snap_id) returns the value that index held when the snapshot snap_id was taken.
Example 1:
Input: {"commands":["SnapshotArray","set","snap","set","get"],"values":[[3],[0,5],[],[0,6],[0,0]]}
Output: [null,null,0,null,5]
Constraints:
  • 1≤length≤5×1041 \leq \text{length} \leq 5 \times 10^4

  • 0≤index<length0 \leq \text{index} < \text{length}

  • 0≤val≤1090 \leq \text{val} \leq 10^9

  • 0≤snap_id<0 \leq \text{snap\_id} < (the total number of times snap() is called)

  • At most 5×1045 \times 10^4 calls are made to set, snap and get.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"commands":["SnapshotArray","set","snap","set","get"],"values":[[3],[0,5],[],[0,6],[0,0]]}
new(3)
set(0,5)
snap()
set(0,6)
get(0,0)

Every one of the 3 indices starts with a one-entry history [snap 0 → 0]. Nothing is copied on snap; each index only records its changes.

snapshot timeline (frozen versions, then the one being edited)

editing 0

per-index history: [snap → value] entries, oldest first

no index has been set yet

3 untouched indices keep only [s0 → 0].

Returned values

[null]
Variables
VariableValue
length3
snap_id0
DepthFunction Call
Stack empty
0/8