Snapshot Array - Problem

Implement a SnapshotArray that supports the following interface:

SnapshotArray(int length) - Initializes an array-like data structure with the given length. Initially, each element equals 0.

void set(index, val) - Sets the element at the given index to be equal to val.

int snap() - Takes a snapshot of the array and returns the snap_id: the total number of times we called snap() minus 1.

int get(index, snap_id) - Returns the value at the given index, at the time we took the snapshot with the given snap_id.

Input & Output

Example 1 — Basic Operations
$ Input: operations = ["SnapshotArray","set","snap","get"], values = [[3],[0,5],[],[0,0]]
Output: [null,null,0,5]
💡 Note: Create array of length 3 [0,0,0]. Set index 0 to 5 [5,0,0]. Take snapshot (returns 0). Get value at index 0 from snapshot 0 returns 5.
Example 2 — Multiple Snapshots
$ Input: operations = ["SnapshotArray","set","snap","set","snap","get","get"], values = [[2],[1,10],[],[1,20],[],[1,0],[1,1]]
Output: [null,null,0,null,1,10,20]
💡 Note: Array [0,0] → set(1,10) → [0,10] → snap() returns 0 → set(1,20) → [0,20] → snap() returns 1. get(1,0) returns 10 from snapshot 0, get(1,1) returns 20 from snapshot 1.
Example 3 — No Changes Before Snap
$ Input: operations = ["SnapshotArray","snap","get"], values = [[1],[],[0,0]]
Output: [null,0,0]
💡 Note: Create array [0], immediately take snapshot (returns 0), get(0,0) returns initial value 0.

Constraints

  • 1 ≤ length ≤ 5 × 104
  • 0 ≤ index < length
  • 0 ≤ val ≤ 109
  • 0 ≤ snap_id < (number of times we call snap())
  • At most 5 × 104 calls will be made to set, snap, and get.

Visualization

Tap to expand
Snapshot Array: Track Historical ValuesOperationsSnapshotArray(3)set(0, 5)snap() → 0Smart StorageIndex 0: [(0,0), (0,5)]Index 1: [(0,0)]Index 2: [(0,0)]Query: get(0, 0)Find latest valuewhere snap_id ≤ 0Binary SearchSearch [(0,0), (0,5)]Return value: 5Result: [null, null, 0, 5]Memory efficient: O(changes) vs O(n × snapshots)
Understanding the Visualization
1
Input
Array operations: create, set, snap, get
2
Process
Track changes with timestamps, not full copies
3
Output
Return results for each operation
Key Takeaway
🎯 Key Insight: Store only changes with timestamps and use binary search for fast historical lookups
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
124.0K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen