
Sponsored
Sponsored
This approach involves using a dictionary to map each index to another dictionary, which maps the snapshot version to the value at that index. Each call to set(index, val) updates our dictionary for the current snapshot version. When snap() is called, it simply increments the snapshot counter and returns the previous version of the snapshot. For get(index, snap_id), we check the dictionary at that index for the most recent version less than or equal to snap_id.
Time Complexity: O(1) for set() and snap(); O(n) worst-case for get(), where n is the number of snapshots.
Space Complexity: O(l + m) where l is the length of the array, and m is the number of set operations.
1class SnapshotArray:
2 def __init__(self, length: int):
3 self.length = length
4 self.snap_id = 0
5 self.snapshots = [{} for _ in range(length)]
6
7 def set(self, index: int, val: int) -> None:
8 self.snapshots[index][self.snap_id] = val
9
10 def snap(self) -> int:
11 self.snap_id += 1
12 return self.snap_id - 1
13
14 def get(self, index: int, snap_id: int) -> int:
15 while snap_id >= 0 and snap_id not in self.snapshots[index]:
16 snap_id -= 1
17 return self.snapshots[index].get(snap_id, 0)The SnapshotArray is initialized with the given length, creating a list of empty dictionaries, one for each index. The current snap_id starts at 0. The set() method updates the dictionary at the given index for the current snap_id. The snap() method returns the current snap_id and then increments it. The get() method searches backwards for the closest snapshot less than or equal to snap_id that has a value set and returns it.
This approach takes advantage of a more compact representation by only storing changes using a sorted list of tuples for each index. Each tuple contains a snapshot_id and the corresponding value. This method optimizes memory usage by skipping the storage of unaltered initial values, effectively treating them as zeroes until explicitly set.
Time Complexity: O(log n) for get() due to binary search; O(1) for set() and snap().
Space Complexity: O(l + m).
1class SnapshotArray {
2 constructor(
In JavaScript, we utilize an array of lists where each list is sorted by snapshot ids. The set() method either updates the last element of the list if the snapshot ids match or appends a new pair. snap() increments the snapshot id. For get(), binary search finds the largest snapshot id less than or equal to snap_id.