SDE & MLE Prep

1146. Snapshot Array

Problem

Design SnapshotArray(length), initially all zeros, with set(index, val), snap() (takes a snapshot and returns its id: the number of snaps before it), and get(index, snap_id) (the value at index when snapshot snap_id was taken).

Example: SnapshotArray(3): set(0,5), snap() → 0, set(0,6), get(0,0) → 5

Constraints: length and number of calls ≤ 5·10⁴.

Don't copy the array on snap. Each index keeps a list of (snap_id, value) changes; get(i, s) = binary search for the last change with snap_id ≤ s.

Complexity: set O(1), snap O(1), get O(log changes).

class SnapshotArray:
    def __init__(self, length: int):
        self.hist = [[(-1, 0)] for _ in range(length)]
        self.snap_id = 0

    def set(self, index: int, val: int) -> None:
        h = self.hist[index]
        if h[-1][0] == self.snap_id:
            h[-1] = (self.snap_id, val)
        else:
            h.append((self.snap_id, val))

    def snap(self) -> int:
        self.snap_id += 1
        return self.snap_id - 1

    def get(self, index: int, snap_id: int) -> int:
        h = self.hist[index]
        i = bisect.bisect_right(h, (snap_id, float("inf"))) - 1
        return h[i][1]