
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.
1#include<algorithm>
2#include<map>
3#include<vector>
4
5class SnapshotArray {
6 int snap_id = 0;
7 std::vector<std::map<int, int>> snapshots;
8
9public:
10 SnapshotArray(int length): snapshots(length) {}
11
12 void set(int index, int val) {
13 snapshots[index][snap_id] = val;
14 }
15
16 int snap() {
17 return snap_id++;
18 }
19
20 int get(int index, int snap_id) {
21 const auto& snap_map = snapshots[index];
22 auto it = snap_map.upper_bound(snap_id);
23 if (it == snap_map.begin()) return 0;
24 --it;
25 return it->second;
26 }
27};We use a vector of maps, where each index in the vector stores a map from snapshot ids to values. The set() method updates the map for the current snapshot. The snap() method increments the snapshot id and returns the previous value. In get(), we find the largest snapshot id less than or equal to the requested one using upper_bound() and return the value. If no such snapshot exists, return 0.
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.