Snapshot Array
Medium
Topics
Implement an array-like structure that can take snapshots and be read back at any earlier snapshot.
SnapshotArray(length) creates an array of length zeros. set(index, val) writes a value. snap() takes a snapshot and returns its id, counting from 0 and increasing by one each time. get(index, snapId) returns the value at that index as of that snapshot.
Example 1
snap does not change any value — it closes the current snapshot and returns its id, counting from 0. A later get reads the value an index held as of that snapshot, so a write after the snap is invisible to it. An index never written reads as 0.Input: operations = ["SnapshotArray","set","snap","set","get"], values = [[3],[0,5],[],[0,6],[0,0]] Output: [null,null,0,null,5] Explanation: Index 0 was set to 5, then snapshot 0 was taken, then it was set to 6. Reading index 0 at snapshot 0 still gives 5.
Constraints
- 1 <= length <= 5 * 10^4
- 0 <= index < length
- 0 <= val <= 10^9
- 0 <= snapId < the number of snaps taken
- At most 5 * 10^4 calls in total.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Copying the whole array on every snap is the obvious reading and the reason the naive version is too slow: the array can be 50,000 long and almost none of it changes between snapshots.
Nothing needs copying, because a snapshot does not change any value — it just draws a line in time. So instead of storing array states, store each index’s history: the snapshot ids at which it changed, with the value it took. A read then asks which of those changes is the most recent one at or before the requested snapshot.
Approach
- Hold, per index, a list of
(snapId, value)pairs — its write history. Keep a counter for the current snapshot id. - On
set, record the value against the current snapshot id, overwriting the last entry if it is already for this id since only the final write before a snap is visible. - On
snap, increment the counter and return the id just closed. - On
get(index, snapId), find the last entry in that index’s history whose id is at mostsnapId. The histories are appended in increasing id order, so that is a binary search. An index never written answers 0.
Walkthrough
SnapshotArray(3) histories all empty, cur = 0
set(0,5) history[0] = [(0,5)]
snap() -> returns 0, cur becomes 1
set(0,6) history[0] = [(0,5), (1,6)]
get(0,0) last entry with id <= 0 -> (0,5) -> 5Complexity
- Time — O(1) per set and snap, O(log k) per get: a set appends or overwrites one entry, a snap bumps a counter, and a get binary-searches the history of a single index, k being its number of writes.
- Space — O(number of writes): one entry per distinct (index, snapshot) write, rather than one copy of the array per snapshot.
Common Pitfalls
- Returning
curfromsnapafter incrementing returns the next id rather than the one just taken. - An index that was never written has no history and must answer 0, not fail.
- Two writes to the same index before a snap must leave only the later value visible at that snapshot.
Full Solution — all languages
class SnapshotArray:
def __init__(self, length):
# one history per index: a list of (snap_id, value), ascending
self.history = [[(0, 0)] for _ in range(length)]
self.snap_id = 0
def set(self, index, val):
hist = self.history[index]
if hist[-1][0] == self.snap_id:
hist[-1] = (self.snap_id, val)
else:
hist.append((self.snap_id, val))
def snap(self):
self.snap_id += 1
return self.snap_id - 1
def get(self, index, snap_id):
import bisect
hist = self.history[index]
i = bisect.bisect_right(hist, (snap_id, float('inf'))) - 1
return hist[i][1]import java.util.*;
class SnapshotArray {
private final List<List<int[]>> history = new ArrayList<>();
private int snapId = 0;
public SnapshotArray(int length) {
for (int i = 0; i < length; i++) {
List<int[]> hist = new ArrayList<>();
hist.add(new int[]{0, 0});
history.add(hist);
}
}
public void set(int index, int val) {
List<int[]> hist = history.get(index);
int[] last = hist.get(hist.size() - 1);
if (last[0] == snapId) last[1] = val;
else hist.add(new int[]{snapId, val});
}
public int snap() {
return snapId++;
}
public int get(int index, int wanted) {
List<int[]> hist = history.get(index);
int lo = 0, hi = hist.size() - 1, best = 0;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (hist.get(mid)[0] <= wanted) {
best = mid;
lo = mid + 1;
} else hi = mid - 1;
}
return hist.get(best)[1];
}
}#include <bits/stdc++.h>
using namespace std;
class SnapshotArray {
public: SnapshotArray(int length) : snapId(0), history(length, { {
0, 0
}
}) {
}
void set(int index, int val) {
auto& hist = history[index];
if (hist.back().first == snapId) hist.back().second = val;
else hist.push_back({snapId, val});
}
int snap() {
return snapId++;
}
int get(int index, int wanted) {
auto& hist = history[index];
int lo = 0, hi = (int)hist.size() - 1, best = 0;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (hist[mid].first <= wanted) {
best = mid;
lo = mid + 1;
} else hi = mid - 1;
}
return hist[best].second;
}
private: int snapId;
vector<vector<pair<int, int>>> history;
};class SnapshotArray {
constructor(length) {
this.history = Array.from({ length }, () => [[0, 0]]);
this.snapId = 0;
}
set(index, val) {
const hist = this.history[index];
if (hist[hist.length - 1][0] === this.snapId) hist[hist.length - 1][1] = val;
else hist.push([this.snapId, val]);
}
snap() {
this.snapId++;
return this.snapId - 1;
}
get(index, snapId) {
const hist = this.history[index];
let lo = 0, hi = hist.length - 1, best = 0;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (hist[mid][0] <= snapId) {
best = mid;
lo = mid + 1;
} else hi = mid - 1;
}
return hist[best][1];
}
}