Snapshot Array
MedPrompt
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 givenindexto be equal toval.int snap()takes a snapshot of the array and returns thesnap_id: the total number of times we calledsnap()minus1.int get(index, snap_id)returns the value at the givenindex, at the time we took the snapshot with the givensnap_id
Example 1:
Input: ["SnapshotArray","set","snap","set","get"]
[[3],[0,5],[],[0,6],[0,0]]
Output: [null,null,0,null,5]
Explanation:
SnapshotArray snapshotArr = new SnapshotArray(3); // set the length to be 3
snapshotArr.set(0,5); // Set array[0] = 5
snapshotArr.snap(); // Take a snapshot, return snap_id = 0
snapshotArr.set(0,6);
snapshotArr.get(0,0); // Get the value of array[0] with snap_id = 0, return 5
Constraints:
1 <= length <= 5 * 1040 <= index < length0 <= val <= 1090 <= snap_id <(the total number of times we callsnap())- At most
5 * 104calls will be made toset,snap, andget.
Approaches
2 approaches with complexity analysis and trade-offs.
This approach is the most straightforward and intuitive. We maintain a current version of the array. Every time snap() is called, we create a complete, deep copy of the current array and store it in a map, using the snap_id as the key. This ensures that we have a perfect record of the array's state for each snapshot.
Algorithm
- Initialize
current_arrayof sizelength, aHashMap<Integer, int[]> snapshots, andsnap_id = 0. set(index, val): Updatecurrent_array[index] = val.snap():- Create a copy:
int[] copy = Arrays.copyOf(current_array, length). - Store the copy:
snapshots.put(snap_id, copy). - Return
snap_id++.
- Create a copy:
get(index, snap_id):- Retrieve the snapshot:
int[] snapshot_array = snapshots.get(snap_id). - Return
snapshot_array[index].
- Retrieve the snapshot:
Walkthrough
In this method, we use a simple integer array, let's call it current_array, to store the most recent state of the data. A HashMap<Integer, int[]> named snapshots is used to store the historical versions of the array, where the key is the snap_id and the value is the array state at that snapshot. A counter snap_id tracks the number of snapshots taken.
SnapshotArray(length): Initializescurrent_arrayof the given length with zeros, initializes thesnapshotsmap, and setssnap_idto 0.set(index, val): Updates the value incurrent_arrayat the given index. This is a constant time operation.snap(): This is the core of this approach. It creates a deep copy ofcurrent_arrayand stores it in thesnapshotsmap with the currentsnap_id. It then incrementssnap_idand returns the ID of the snapshot just created. The copy operation takes time proportional to the length of the array.get(index, snap_id): Retrieves the array corresponding to the givensnap_idfrom thesnapshotsmap and then returns the element at the specifiedindex.
import java.util.Arrays;import java.util.HashMap;import java.util.Map; class SnapshotArray { private int[] current_array; private Map<Integer, int[]> snapshots; private int snap_id; public SnapshotArray(int length) { current_array = new int[length]; snapshots = new HashMap<>(); snap_id = 0; } public void set(int index, int val) { current_array[index] = val; } public int snap() { int[] copy = Arrays.copyOf(current_array, current_array.length); snapshots.put(snap_id, copy); return snap_id++; } public int get(int index, int snap_id) { int[] snapshot_array = snapshots.get(snap_id); return snapshot_array[index]; }}Complexity
Time
- **Constructor**: O(L) to initialize the array. - **`set`**: O(1). - **`snap`**: O(L) due to the array copying. - **`get`**: O(1) for HashMap lookup.
Space
O(S * L), where S is the number of snapshots and L is the array length. This is because for each of S snapshots, we store a full copy of the array of length L.
Trade-offs
Pros
Simple to understand and implement.
setandgetoperations are very fast (O(1)).
Cons
snap()operation is slow, with a time complexity of O(L), where L is the length of the array.Extremely high space complexity (O(S * L), where S is the number of snapshots), making it infeasible for large inputs.
Solutions
Solution
class SnapshotArray { private List < int []>[] arr ; private int idx ; public SnapshotArray ( int length ) { arr = new List [ length ]; Arrays . setAll ( arr , k -> new ArrayList <>()); } public void set ( int index , int val ) { arr [ index ]. add ( new int [] { idx , val }); } public int snap () { return idx ++; } public int get ( int index , int snap_id ) { var vals = arr [ index ]; int left = 0 , right = vals . size (); while ( left < right ) { int mid = ( left + right ) >> 1 ; if ( vals . get ( mid )[ 0 ] > snap_id ) { right = mid ; } else { left = mid + 1 ; } } return left == 0 ? 0 : vals . get ( left - 1 )[ 1 ]; } } /** * Your SnapshotArray object will be instantiated and called as such: * SnapshotArray obj = new SnapshotArray(length); * obj.set(index,val); * int param_2 = obj.snap(); * int param_3 = obj.get(index,snap_id); */Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.