Snapshot array
Implement a SnapshotArray that supports setting values, taking snapshots of its current state, and retrieving historical values based on snapshot IDs.
Implement the SnapshotArray class:
- SnapshotArray(int length): Initializes an array-like data structure with the given length. Initially, each element equals 0.
- void set(int index, int val): Sets the element at the given index to be equal to val.
- int snap(): Takes a snapshot of the array and returns the snap_id: the total number of times we called snap() minus 1.
- int get(int index, int snap_id): Returns the value at the given index, at the time we took the snapshot with the given snap_id.
(Note: For testing purposes, the input is provided as an array of commands strings and a 2D array of args representing the sequence of method calls. The output will only capture the integers returned by the snap and get methods.)
Example 1:
Input: ["SnapshotArray","set","snap","set","get"] [[3],[0,5],[],[0,6],[0,0]]
Output: [null,null,0,null,5]
Explanation:
SnapshotArray(3): Array is initialized to [0, 0, 0].
- set(0, 5): Array becomes [5, 0, 0].
- snap(): Takes snapshot, returns snap_id = 0.
- set(0, 6): Array becomes [6, 0, 0].
- get(0, 0): Returns the value at index 0 during snap_id 0, which was 5.
Example 2:
Input: ["SnapshotArray","set","snap","snap","get"] [[1],[0,15],[],[],[0,1]]
Output: [null,null,0,1,15]
Explanation:
The value at index 0 is set to 15. We take a snapshot (snap_id 0), then immediately take another (snap_id 1). Getting the value at index 0 for snap_id 1 correctly returns 15.
Now Your Turn!
Pick the correct output for the given inputInput: commands = ["SnapshotArray", "set", "snap", "get"] args = [[2], [1, 10], [], [0, 0]]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= length <= 5*104
- 0 <= index < length
- 0 <= val <= 109
- 0 <= snap_id < (total number of times snap() has been called)
- At most 5*104 total calls will be made to set, snap, and get.