Snapshot Array Problem
Description
LeetCode Problem 1146.
Implement a SnapshotArray that supports the following interface:
SnapshotArray(int length)initializes an array-like data structure with the given length. Initially, each element equals 0.void set(index, val)sets the element at the givenindexto be equal toval.int snap()takes a snapshot of the array and returns thesnap_id: the total number of times we calledsnap()minus1.int get(index, snap_id)returns the value at the givenindex, at the time we took the snapshot with the givensnap_id
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
Constraints:
1 <= length <= 5 * 10^40 <= index < length0 <= val <= 10^90 <= snap_id <(the total number of times we callsnap())- At most
5 * 10^4calls will be made toset,snap, andget.
Solution
Approach: Per-Index Change History + Binary Search
Copying the whole array on every snap() would cost O(length) time and memory per snapshot, which is far too much with up to 5 * 10^4 of each. Most indices do not change between two snapshots, so store only the changes.
Keep a counter snapId: the id of the snapshot currently being built, starting at 0. For every index keep a list of (snap id, value) pairs:
set(index, val)appends(snapId, val)to that index's list. If the last entry already has the same snap id, the index was changed twice before a snap, and only the latest value matters, so overwrite it.snap()returnssnapIdand then increments it. Nothing is copied.get(index, snap_id): the value at that snapshot is the one from the last change made in a snapshot with id<= snap_id. The snap ids in each list are increasing, so binary search finds it. If there is no such change, the element was never set before that snapshot and is still0.
The tricky part is the off-by-one: a set made after snapshot k was taken belongs to snapshot k + 1, so it must not show up in get(index, k). This works because snap() increments the counter, and set always records the current counter.
Complexity: O(1) for set and snap, O(log s) for get, where s is the number of changes stored for that index. Space is O(length + number of set calls).
import bisect
class SnapshotArray:
def __init__(self, length: int):
# For each index, the history of its changes: snap ids (increasing) and the value set in that snap.
self.ids = [[] for _ in range(length)]
self.vals = [[] for _ in range(length)]
self.snap_id = 0 # id of the snapshot being built right now
def set(self, index: int, val: int) -> None:
ids, vals = self.ids[index], self.vals[index]
if ids and ids[-1] == self.snap_id:
vals[-1] = val # changed again before the next snap: overwrite
else:
ids.append(self.snap_id)
vals.append(val)
def snap(self) -> int:
self.snap_id += 1
return self.snap_id - 1
def get(self, index: int, snap_id: int) -> int:
# The last change made in a snap with id <= snap_id.
i = bisect.bisect_right(self.ids[index], snap_id) - 1
return self.vals[index][i] if i >= 0 else 0
# Your SnapshotArray object will be instantiated and called as such:
# obj = SnapshotArray(length)
# obj.set(index,val)
# param_2 = obj.snap()
# param_3 = obj.get(index,snap_id)