1146. Snapshot Array
Asked at 17Apple64Google33Amazon25Microsoft23Meta5.0MongoDB100Verkada76Coupang68TikTok68Rubrik66Databricks63Aurora62Nutanix60Snowflake54Netflix49OpenAI49Goldman Sachs21
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]
sa = SnapshotArray(3)
sa.set(0, 5)
assert sa.snap() == 0
sa.set(0, 6)
assert sa.get(0, 0) == 5 and sa.get(0, 1) == 6 and sa.get(1, 0) == 0
class SnapshotArray {
private final List<TreeMap<Integer, Integer>> hist = new ArrayList<>();
private int snapId = 0;
public SnapshotArray(int length) {
for (int i = 0; i < length; i++) {
TreeMap<Integer, Integer> t = new TreeMap<>();
t.put(-1, 0);
hist.add(t);
}
}
public void set(int index, int val) { hist.get(index).put(snapId, val); }
public int snap() { return snapId++; }
public int get(int index, int snap_id) { return hist.get(index).floorEntry(snap_id).getValue(); }
}
type SnapshotArray struct {
hist [][][2]int // per index: (snap id, value) changes, in snap order
snapID int
}
func Constructor(length int) SnapshotArray {
hist := make([][][2]int, length)
for i := range hist {
hist[i] = [][2]int{{-1, 0}} // everything starts at 0
}
return SnapshotArray{hist: hist}
}
func (this *SnapshotArray) Set(index int, val int) {
h := this.hist[index]
if h[len(h)-1][0] == this.snapID { // overwrite within the same snapshot
h[len(h)-1][1] = val
} else {
this.hist[index] = append(h, [2]int{this.snapID, val})
}
}
func (this *SnapshotArray) Snap() int {
this.snapID++
return this.snapID - 1
}
func (this *SnapshotArray) Get(index int, snap_id int) int {
h := this.hist[index]
i := sort.Search(len(h), func(k int) bool { return h[k][0] > snap_id }) - 1 // last change at or before snap_id
return h[i][1]
}