916. Versioned Array
An editor keeps a long numeric strip and lets users freeze its state. Build the class VersionedArray. The constructor receives length, the number of cells, all initially 0.
assign(index, val)writesvalinto the cellindex(0-based).snap()freezes the whole strip and returns the id of the new snapshot. Ids are 0, 1, 2, ... in the order the snapshots are taken.get(index, snapId)returns the value that cellindexhad at the moment snapshotsnapIdwas taken. Later writes do not affect it.
Copying the full strip at each snap is too slow and too big when the strip is huge: make snap cost O(1), assign cost O(1) and get cost O(log s) where s is the number of changes of that cell.
Example 1
- Input:
- operations = ["VersionedArray","assign","snap","assign","get","snap","get","get"]arguments = [[4],[2,71],[],[2,88],[2,0],[],[2,1],[0,1]]
- Output:
- [null,null,0,null,71,1,88,0]
- Explanation:
The first snapshot (id 0) captures 71 at index 2. Index 2 later becomes 88, which snapshot 1 captures, while snapshot 0 still reads 71. Index 0 was never set, so it reads 0.
Example 2
- Input:
- operations = ["VersionedArray","snap","assign","assign","snap","get","get"]arguments = [[3],[],[1,5],[1,6],[],[1,0],[1,1]]
- Output:
- [null,0,null,null,1,0,6]
- Explanation:
Setting the same cell twice before a snapshot keeps only the last value (6). Snapshot 0 was taken before any write, so it reads 0.
Constraints
1 ≤ length ≤ 106
0 ≤ index < length, 0 ≤ val ≤ 109
get is only called with snapId smaller than the number of snapshots taken so far
At most 50000 calls in total
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Input
- Each case is an operation log.
operationsnames the class first and then each method call;argumentsholds the arguments for each, in the same order. Your answer is one list with a result per operation -nullfor the constructor and for methods that return nothing.
Expected complexity
- Time
- O(1) set/snap, O(log s) get
- Space
- O(number of set calls)