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_idExample 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 call snap())5 * 104 calls will be made to set, snap, and get.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a notebook where you can change numbers and take pictures of the pages over time. The brute force approach creates a brand new copy of the entire notebook every single time a picture is requested, storing every page separately.
Here's how the algorithm would work step-by-step:
class SnapshotArray:
# Initialize the array container and photo album to track history
def __init__(self, array_length: int):
self.current_notebook_page = [0] * array_length
self.photo_album = []
def set(self, index_to_update: int, new_number_value: int) -> None:
self.current_notebook_page[index_to_update] = new_number_value
def snap(self) -> int:
# Duplicate the entire notebook state to preserve history for future queries
self.photo_album.append(list(self.current_notebook_page))
return len(self.photo_album) - 1
def get(self, index_to_query: int, snapshot_identifier: int) -> int:
# Retrieve the specific historical notebook copy from the photo album
target_notebook_page = self.photo_album[snapshot_identifier]
return target_notebook_page[index_to_query]Instead of making a physical copy of all values every time a snapshot is taken, which would waste a huge amount of time and space, we only record the specific changes made to individual items along with the corresponding snapshot version. When we need to look up a value from a past snapshot, we simply search through the history of that specific item to find what it was at that exact moment.
Here's how the algorithm would work step-by-step:
import bisect
class SnapshotArray:
def __init__(self, array_length):
self.current_snapshot_id = 0
self.history_records = [[[0, 0]] for _ in range(array_length)]
def set(self, index_to_modify, new_value):
# We append history to avoid copying the entire array on every change.
self.history_records[index_to_modify].append([self.current_snapshot_id, new_value])
def snap(self):
self.current_snapshot_id += 1
return self.current_snapshot_id - 1
def get(self, index_to_query, target_snapshot_id):
# Binary search locates the latest valid state for the requested snapshot version.
target_history = self.history_records[index_to_query]
insertion_index = bisect.bisect_right(target_history, [target_snapshot_id + 1, -1])
return target_history[insertion_index - 1][1]| Case | How to Handle |
|---|---|
| Setting values for an index multiple times before taking any snapshot | Updating the latest entry in the history list for that index avoids redundant snapshot records and saves memory. |
| Querying a snapshot id where no sets were ever performed on that index | Using binary search on the history list successfully falls back to the initial value of zero. |
| Taking a snapshot without making any modifications to the array beforehand | Incrementing the global snap_id correctly records the current timeline state without needing duplicate value copies. |
| Querying a snapshot id that is older than the first modification made to the index | Binary search naturally returns the default zero value when no historical record exists at or before the requested snap_id. |
| Maximum possible snapshot ID and large number of set operations leading to memory bloat | Storing only the modified indices and their snap_id timestamps avoids allocating full array copies for every snapshot. |
| Array initialized with the maximum allowed length constraint | Pre-allocating a list of history structures of the exact given length ensures constant-time index access. |
| Multiple rapid snapshots taken without intervening set operations | Maintaining a global snapshot counter increments correctly while the index history remains unchanged until the next set operation. |
| Querying a snap_id that matches the exact timestamp when a set operation occurred | Binary search uses an upper bound or less-than-or-equal condition to correctly locate and return the value set at that exact snapshot. |