#1146

Snapshot Array

expert · 1055 · lc medium +32 · 36.7% accepted · 3,915 likes · top 14%

Description

Build a SnapshotArray data structure that supports these operations:

- SnapshotArray(int length) constructs the structure with the given length, initializing all elements to 0.

- void set(index, val) updates the element at position index to val.

- int snap() captures the current state of the array and returns the snap_id, equal to the number of previous snap() calls.

- int get(index, snap_id) retrieves the value at position index as it was when the snapshot with the given snap_id was taken.

Example 1:

Input: ["SnapshotArray","set","snap","set","get"]
[[3],[0,5],[],[0,6],[0,0]]
Output: [null,null,0,null,5]
Explanation:
SnapshotArray snapshotArr = new SnapshotArray(3); // set the length to be 3
snapshotArr.set(0,5); // Set array[0] = 5
snapshotArr.snap(); // Take a snapshot, return snap_id = 0
snapshotArr.set(0,6);
snapshotArr.get(0,0); // Get the value of array[0] with snap_id = 0, return 5

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20