Snapshot Array (LeetCode 1146): Solution and Explanation

Medium
Array
Hash Table
Binary Search
Design

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

  1. In the constructor, set snap_id = 0 and give every index the history [[0, 0]].
  2. set(index, val): look at the newest entry of that index. If its snap id equals the current snap_id, overwrite its value. Otherwise append [snap_id, val].
  3. snap(): increment snap_id and return the previous value.
  4. get(index, snap_id): binary search the index's history for the largest position whose snap id is at most snap_id, using mid = (lo + hi + 1) // 2 so 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]]
  1. SnapshotArray(3): indices 0, 1 and 2 each hold the history [[0, 0]]. snap_id is 0.
  2. 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]].
  3. snap(): return 0 and move snap_id to 1. Nothing is copied.
  4. 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]].
  5. 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.
  6. 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]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

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.

Space

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) // 2 with lo = mid. When hi = lo + 1 the midpoint never moves and the loop runs forever; round up instead.
  • Returning snap_id after incrementing it. The first snap() must return 0.
  • Forgetting the starting [0, 0] entry. Without it, a get on 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.