0:00 / 0:00

Take snapshots of a huge array cheaply: each index keeps only its changes, and a binary search finds the value at any snap id.

▼

The problem

LeetCode 1146 (Medium). Implement SnapshotArray(length): an array of length zeros with set(index, val), snap() (takes a snapshot and returns its snap_id, the number of snaps taken minus 1) and get(index, snap_id) (the value at index when snap snap_id was taken).

Example (LeetCode's, scene 2): SnapshotArray(3), set(0, 5), snap() → 0, set(0, 6), get(0, 0) → 5.

TRY IT ON LEETCODE ▶

The solution

from bisect import bisect_right
from math import inf

class SnapshotArray:
    def __init__(self, length):
        self.snap_id = 0
        self.hist = [[(-1, 0)] for _ in range(length)]
    def set(self, index, val):
        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):
        self.snap_id += 1
        return self.snap_id - 1
    def get(self, index, snap_id):
        h = self.hist[index]
        i = bisect_right(h, (snap_id, inf)) - 1
        return h[i][1]

Transcript

Snapshot Array. Build an array of zeros with three moves. Set puts a value at an index. Snap saves the array and returns a snap id: zero, then one, then two. Get reads an index as it was at a given snap.

LeetCode's example has length three. Set index zero to five. Snap returns zero. Set index zero to six. Get index zero at snap zero: the array holds six now, but snap zero saw five.

The simple way copies the whole array on every snap: order n per snap. Fifty thousand slots and fifty thousand snaps would store two and a half billion values, almost all repeats.

Better: record changes, not copies. Each index keeps a history of pairs: the snap id when it was set, and the value. Every history starts with a zero. Set appends a pair, but if the last pair already has the current snap id, it overwrites it. Snap copies nothing; it just bumps a counter.

To get, search that index's history for the last pair whose snap id is at or before the one you asked for. Snap ids only grow, so every history is sorted, and binary search finds it in log time.

A longer, illustrative session on index one. It gets four, then snap zero. Seven, then snaps one and two. Two, overwritten by nine, then snap three. Five, then snap four. Get index one at snap two. The middle pair is snap one: early enough, go right. Snap four is too late: go left. Snap three, too late. The answer is the pair before: seven.

In code, set overwrites or appends on one list. Snap bumps the counter and returns the old id. Get is bisect right on the history, minus one.

Set and snap take constant time. Get takes log of that index's history length. Memory grows with the sets, never with the snaps.

Record the changes, count the snaps, search the history. That's Snapshot Array.