Snapshot Array solution explained
Snapshot Array asks for an array that can take numbered snapshots and later answer what any index held at any past snapshot. Copying the whole array on every snapshot is too expensive, so each index keeps its own short log of (snapshot id, value) changes. A read binary-searches that log for the last change at or before the requested snapshot, which makes set and snap O(1) and get O(log c), where c is the number of changes to that index.
By Evin JohnPublished 8 min read
The task, restated
Create an array of a given length where every value starts at 0. set(index, value) changes the current value at that index. snap() freezes the current state and returns its id; the first snapshot is 0, the next 1, and so on. get(index, snap_id) returns what index held at the moment snapshot snap_id was taken. Changes made after the latest snapshot are not visible through any existing id. The array can be long, and the number of calls can be large, so neither memory nor time may grow with length times snapshots.
| Call | Returns | Note |
|---|---|---|
| set(1, 5) | change during epoch 0 | |
| snap() | 0 | snapshot 0 sees index 1 = 5 |
| set(1, 6) | epoch 1 | |
| set(2, 9) | epoch 1 | |
| snap() | 1 | |
| snap() | 2 | nothing changed in between |
| set(1, 7) | epoch 3, not yet frozen | |
| get(1, 0) | 5 | |
| get(1, 2) | 6 | snapshot 2 inherits from snapshot 1 |
| get(2, 0) | 0 | index 2 was untouched at snapshot 0 |
| get(3, 1) | 0 | never set at all |
A useful word for this problem is epoch: the stretch of time between two snapshots. Every set belongs to the epoch whose number equals the id the next snap() will return. Thinking in epochs makes the overwrite rule obvious: two sets to the same index in one epoch only need the last value.
Why interviewers like it
Snapshot Array is a compact way to test versioned data, which shows up in databases, editors with undo history, and configuration systems. It also checks whether you can spot binary search in a design question, where it is less obvious than in a sorted-array puzzle. Follow-ups usually probe the design further:
- Most indexes never change. Allocate logs lazily, only for indexes that were set, so memory tracks the number of changes, not the length.
- Reads are far more common than writes. The binary search is already cheap; you could cache the last answer per index if reads repeat.
- Delete old snapshots. Trim log entries older than the oldest snapshot still needed, keeping the last one before it.
- Snapshots of a whole map, not an array. The same per-key log works; this is how multiversion storage engines think about rows.
A slow start: copy everything
The direct design keeps the live array and, on each snap, stores a full copy. get reads the copy for that id. Reads are O(1), but each snapshot costs O(n) time and O(n) memory, so a long array with many snapshots runs out of memory long before it runs out of time. It is still the right reference for testing.
class CopyingSnapshots:
def __init__(self, length):
self.live = [0] * length
self.frozen = []
def set(self, index, val):
self.live[index] = val
def snap(self):
self.frozen.append(self.live[:])
return len(self.frozen) - 1
def get(self, index, snap_id):
return self.frozen[snap_id][index]Optimal approach: a change log per index
For each index that has ever been set, keep two parallel lists: the epoch ids at which it changed, in increasing order, and the values it changed to. set appends to the logs of that index, or overwrites the last value if the last recorded id is the current epoch. snap only increments the epoch counter. get(index, snap_id) looks for the rightmost recorded id that is less than or equal to snap_id. If there is none, the index still held its starting 0 at that snapshot.
from bisect import bisect_right
class SnapshotArray:
def __init__(self, length):
self.length = length
self.epoch = 0
self.ids = {} # index -> epochs where it changed, increasing
self.vals = {} # index -> values, aligned with ids
def set(self, index, val):
ids = self.ids.setdefault(index, [])
vals = self.vals.setdefault(index, [])
if ids and ids[-1] == self.epoch:
vals[-1] = val
else:
ids.append(self.epoch)
vals.append(val)
def snap(self):
self.epoch += 1
return self.epoch - 1
def get(self, index, snap_id):
ids = self.ids.get(index)
if not ids:
return 0
k = bisect_right(ids, snap_id) - 1
return self.vals[index][k] if k >= 0 else 0class SnapshotArray {
constructor(length) {
this.length = length;
this.epoch = 0;
this.logs = new Map();
}
set(index, val) {
if (!this.logs.has(index)) this.logs.set(index, { ids: [], vals: [] });
const log = this.logs.get(index);
const n = log.ids.length;
if (n > 0 && log.ids[n - 1] === this.epoch) {
log.vals[n - 1] = val;
} else {
log.ids.push(this.epoch);
log.vals.push(val);
}
}
snap() {
this.epoch += 1;
return this.epoch - 1;
}
get(index, snapId) {
const log = this.logs.get(index);
if (!log) return 0;
let lo = 0;
let hi = log.ids.length - 1;
let found = -1;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (log.ids[mid] <= snapId) {
found = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return found === -1 ? 0 : log.vals[found];
}
}bisect_right returns the position just after the last id that is less than or equal to snap_id, so subtracting one lands on the entry you want, or on -1 when every change came later. The JavaScript loop does the same thing explicitly: it remembers the last midpoint that satisfied the condition and keeps searching to the right.
Trace for index 1
| Query | ids | vals | Rightmost id at or below the query | Answer |
|---|---|---|---|---|
| get(1, 0) | [0, 1, 3] | [5, 6, 7] | 0 | 5 |
| get(1, 1) | [0, 1, 3] | [5, 6, 7] | 1 | 6 |
| get(1, 2) | [0, 1, 3] | [5, 6, 7] | 1, since 3 is too new | 6 |
The entry with id 3 records set(1, 7), made after snapshot 2. It sits in the log but no existing snapshot can see it. If a fourth snap() is taken, it will return 3 and that value becomes visible.
Time and space
| Design | set | snap | get | Space |
|---|---|---|---|---|
| Copy on snap | O(1) | O(n) | O(1) | O(n times S) |
| Per-index logs, binary search | O(1) amortized | O(1) | O(log c) | O(C) |
| Per-index logs, linear scan backward | O(1) amortized | O(1) | O(c) | O(C) |
Edge cases
- get on an index that was never set returns 0 for every snapshot.
- get on an index whose first change came after the requested snapshot returns 0.
- Several sets to one index in one epoch leave a single log entry holding the last value.
- snap() with no changes since the last one still returns a fresh id, and it sees the same values as the previous snapshot.
- Setting a value back to 0 is a real change and must be logged, or older snapshots and newer ones become indistinguishable.
Mistakes to avoid
- Returning the epoch counter after incrementing it, so the first snapshot gets id 1.
- Using bisect_left, which skips an entry whose id equals snap_id.
- Appending a new entry for every set, even in the same epoch, which inflates the logs and can break a search that assumes unique ids.
- Allocating a log for every index up front when the length is huge and most indexes never change.
- Assuming the latest value is the answer for the latest snapshot, forgetting that changes after the last snap are not visible yet.
How to explain it out loud
Fictional example
- Candidate
- Copying the array per snapshot costs length times snapshots in memory, so instead each index keeps a log of the epochs where it changed and the values.
- Candidate
- Set appends to that log, or overwrites the last entry if it is from the current epoch. Snap just bumps the epoch counter and returns the old value.
- Candidate
- Get finds the last logged epoch at or before the snapshot id with a binary search. If there is none, the answer is zero. So set and snap are constant and get is log of the changes for that index.
Related problems
Design Underground System records events over time but only ever needs running totals, a useful contrast to keeping full history here. Random Pick With Weight is the other problem in this group that hides a rightmost-or-leftmost binary search inside a design. LFU Cache is a good next design question if you want more practice keeping several structures in step.
Natively in your practice
Natively runs on Mac and Windows and, in practice sessions, can read a prompt like this from a screenshot or from the page through its Chrome extension, then propose code for comparison. It also keeps a transcript of what you said. For this problem, the transcript is the useful part: it shows whether you justified bisect_right over bisect_left out loud. Read more on the AI interview assistant page.
Questions people ask
How do you solve Snapshot Array?
For each index that has been set, keep a log of the snapshot ids where it changed and the values. set appends or overwrites the entry for the current epoch, snap increments a counter, and get binary-searches for the last logged id at or below snap_id, or returns 0 if there is none.
What is the time complexity of Snapshot Array?
set is O(1) amortized, snap is O(1) and get is O(log c), where c is the number of changes logged for that index. Space is O(C) for all logged changes, instead of copying the whole array on every snapshot.
Should Snapshot Array use bisect_left or bisect_right?
bisect_right. It returns the position just after the last id that is less than or equal to snap_id, so subtracting one lands on the right entry. bisect_left skips an entry whose id equals snap_id.
Why not copy the array on every snapshot?
Each snapshot would cost O(n) time and O(n) memory, so a long array with many snapshots runs out of memory. It is still a good reference for testing the faster design.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
