Snapshot Array (LeetCode 1146): Solution and Explanation
Build an array of a given length, all zeros, that supports set(index, val), snap() which freezes the current contents and returns a snapshot id, and get(index, snap_id) which reads what an index held in an old snapshot.
Intuition
The literal approach copies the whole array on every snap(). With 50,000 elements and 50,000 calls that is billions of copied values, and almost all of them are identical to the previous copy, because a single set changes one index.
So flip the storage around. Instead of one full array per snapshot, keep one short history per index that records only when that index changed. Each entry is a pair [snap_id, value] meaning "from this snapshot on, the value is this". Every index starts with [0, 0].
Now snap() copies nothing: it just bumps a counter. A set during snapshot s either overwrites the newest entry (if that entry was already written during s, since no snapshot has frozen it yet) or appends [s, val].
Each history is sorted by snap id because ids only grow. To answer get(index, snap_id), find the last entry whose snap id is at most snap_id. That entry is the value that was live when the snapshot was taken, and binary search finds it in O(log k).
Approach: Per-index change history with binary search
- In the constructor, set
snap_id = 0and give every index the history[[0, 0]]. set(index, val): look at the newest entry of that index. If its snap id equals the currentsnap_id, overwrite its value. Otherwise append[snap_id, val].snap(): incrementsnap_idand return the previous value.get(index, snap_id): binary search the index's history for the largest position whose snap id is at mostsnap_id, usingmid = (lo + hi + 1) // 2so the search moves right on a match, and return that entry's value.
Step-by-step example
["SnapshotArray","set","snap","set","get"], [[3],[0,5],[],[0,6],[0,0]]
- SnapshotArray(3): indices 0, 1 and 2 each hold the history [[0, 0]].
snap_idis 0. - set(0, 5): the newest entry of index 0 is [0, 0], written during snap 0, which is still being edited. Overwrite it, so index 0 holds [[0, 5]].
- snap(): return 0 and move
snap_idto 1. Nothing is copied. - set(0, 6): the newest entry [0, 5] belongs to snap 0, which is now frozen. Append [1, 6], so index 0 holds [[0, 5], [1, 6]].
- get(0, 0): lo = 0, hi = 1, mid = 1. Entry 1 was written at snap 1, which is newer than 0, so hi = 0. The loop ends at lo = 0 and returns 5.
- The output is [null, null, 0, null, 5].
Code: Python, Java, C++
1class SnapshotArray:
2 def __init__(self, length: int):
3 self.snap_id = 0
4 self.history = [[[0, 0]] for _ in range(length)]
5
6 def set(self, index: int, val: int) -> None:
7 cell = self.history[index]
8 if cell[-1][0] == self.snap_id:
9 cell[-1][1] = val
10 else:
11 cell.append([self.snap_id, val])
12
13 def snap(self) -> int:
14 self.snap_id += 1
15 return self.snap_id - 1
16
17 def get(self, index: int, snap_id: int) -> int:
18 cell = self.history[index]
19 lo, hi = 0, len(cell) - 1
20 while lo < hi:
21 mid = (lo + hi + 1) // 2
22 if cell[mid][0] <= snap_id:
23 lo = mid
24 else:
25 hi = mid - 1
26 return cell[lo][1]1class SnapshotArray {
2 private List<List<int[]>> history;
3 private int snapId = 0;
4
5 public SnapshotArray(int length) {
6 history = new ArrayList<>();
7 for (int i = 0; i < length; i++) {
8 List<int[]> cell = new ArrayList<>();
9 cell.add(new int[]{0, 0});
10 history.add(cell);
11 }
12 }
13
14 public void set(int index, int val) {
15 List<int[]> cell = history.get(index);
16 int[] last = cell.get(cell.size() - 1);
17 if (last[0] == snapId) {
18 last[1] = val;
19 } else {
20 cell.add(new int[]{snapId, val});
21 }
22 }
23
24 public int snap() {
25 snapId++;
26 return snapId - 1;
27 }
28
29 public int get(int index, int snap_id) {
30 List<int[]> cell = history.get(index);
31 int lo = 0, hi = cell.size() - 1;
32 while (lo < hi) {
33 int mid = (lo + hi + 1) / 2;
34 if (cell.get(mid)[0] <= snap_id) {
35 lo = mid;
36 } else {
37 hi = mid - 1;
38 }
39 }
40 return cell.get(lo)[1];
41 }
42}1class SnapshotArray {
2 int snapId = 0;
3 vector<vector<pair<int, int>>> history;
4
5public:
6 SnapshotArray(int length) {
7 history.assign(length, vector<pair<int, int>>{{0, 0}});
8 }
9
10 void set(int index, int val) {
11 auto& cell = history[index];
12 if (cell.back().first == snapId) {
13 cell.back().second = val;
14 } else {
15 cell.push_back({snapId, val});
16 }
17 }
18
19 int snap() {
20 snapId++;
21 return snapId - 1;
22 }
23
24 int get(int index, int snap_id) {
25 auto& cell = history[index];
26 int lo = 0, hi = (int) cell.size() - 1;
27 while (lo < hi) {
28 int mid = (lo + hi + 1) / 2;
29 if (cell[mid].first <= snap_id) {
30 lo = mid;
31 } else {
32 hi = mid - 1;
33 }
34 }
35 return cell[lo].second;
36 }
37};Time and space complexity
O(1) set and snap, O(log k) get
set touches only the last entry of one list, and snap increments a counter. get binary searches one index's history, where k is the number of times that index changed in distinct snapshots.
O(length + s)
Each index starts with one entry, and each set adds at most one more, so memory grows with the array length plus the number of set calls s.
Other approaches
Copy the array on every snap (time O(length) per snap, O(1) get, space O(length × snaps))
Store a full copy of the array per snapshot. get is a plain lookup, but each snap costs O(length) time and memory, which is too slow and too large at the limits.
Dirty map per snapshot (time O(1) set and snap, O(snaps) get, space O(length + s))
Keep a map of only the indices changed since the last snapshot, and save that map on snap. A get then has to walk backward through snapshot maps until it finds the index, which is O(snaps) in the worst case.
Common mistakes
- Always appending on
set. Two sets in the same snapshot would leave two entries with the same snap id, and binary search may return the older value. - Using
mid = (lo + hi) // 2withlo = mid. When hi = lo + 1 the midpoint never moves and the loop runs forever; round up instead. - Returning
snap_idafter incrementing it. The firstsnap()must return 0. - Forgetting the starting
[0, 0]entry. Without it, ageton an index that was only set in later snapshots has nothing to fall back on.
Frequently asked questions
Why can set overwrite the newest entry instead of always appending?
An entry written during the current snap id is not part of any snapshot yet, because that snapshot has not been taken. Only the last value written before snap() matters for it, so overwriting is safe and keeps the history short.
Why is each history sorted, so binary search works?
Entries are only ever appended with the current snap id, and the snap id never decreases. So every history is in increasing snap id order with no duplicates.
Could I use bisect in Python?
Yes. Store two parallel lists per index, snap ids and values, and use bisect_right(snaps, snap_id) - 1 to find the entry. It is the same O(log k) search.
What if get asks for an index that was never set?
Its history is still [[0, 0]], so the search lands on that entry and returns 0, which is the initial value.