Snapshot Array

Medium

Topics
ArrayHash TableBinary SearchDesign

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

returnsSnapshotArray(3)set(0, 5)snap()0set(0, 6)get(0, 0)5
A 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.
Calls run top to bottom; the arrow shows what each one returns.
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

  1. Hold, per index, a list of (snapId, value) pairs — its write history. Keep a counter for the current snapshot id.
  2. 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.
  3. On snap, increment the counter and return the id just closed.
  4. On get(index, snapId), find the last entry in that index’s history whose id is at most snapId. 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) -> 5

Complexity

  • 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 cur from snap after 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]
SensAI
Beta
Tap the mic to stop voice mode