Taro Logo

Snapshot Array

#1 Most AskedMedium
0 views
Topics:
ArraysBinary Search

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

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 * 104
  • 0 <= index < length
  • 0 <= val <= 109
  • 0 <= snap_id < (the total number of times we call snap())
  • At most 5 * 104 calls will be made to set, snap, and get.

Solution


Clarifying Questions

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:

  1. What are the constraints on the length of the array and the total number of `snap()` and `set()` operations we should expect?
  2. Can `set()` be called on indices that have already been snapshotted multiple times within the same snapshot epoch, and how should out-of-bounds indices be handled?
  3. What is the range of values that can be passed to the `set()` method (e.g., are negative numbers or large integers possible)?
  4. How should the snapshot ID returned by `snap()` be formatted or generated (e.g., is it a sequential integer starting from 0)?
  5. Is the historical value retrieval via `get(index, snap_id)` guaranteed to reference a valid `snap_id` that has already been created?

Brute Force Solution

Approach

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:

  1. Start with a fresh notebook where all numbers begin at zero.
  2. Whenever a number is changed, update it in the current notebook page.
  3. Whenever a picture is requested, make a complete duplicate of the entire notebook exactly as it looks at that moment and store it in a photo album.
  4. Whenever someone asks for a number from a specific picture in the past, open that exact stored notebook copy and look up the number.
  5. Repeat this copying process for every single picture request made throughout the entire history.

Code Implementation

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]

Big(O) Analysis

Time Complexity
O(S * N) – For each of the S snapshot requests made throughout history, we are forced to duplicate the entire array of size N to store the state. Setting values takes constant time, but every single snapshot operation iterates through all N elements to copy them into a brand-new notebook. This duplication process repeats for each of the S snapshots, leading to approximately S * N operations in total. Simplifying this multiplication of the number of snapshots and the array size gives a final time complexity of O(S * N).
Space Complexity
O(S * N) – The brute force approach uses auxiliary memory by creating and storing a complete duplicate of the notebook array every single time a picture is requested. If there are N elements in the array and S snapshots are taken, this requires storing S separate copies of size N. Therefore, the total extra memory grows linearly with both the number of array elements and the total number of snapshots.

Optimal Solution

Approach

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:

  1. Maintain a timeline of changes for each item, where every update records both the new value and the current snapshot version number.
  2. Whenever an item's value changes, add a new entry to its personal timeline detailing the current snapshot version and the new value.
  3. When a snapshot is requested, simply advance a global counter representing the current version without copying any data.
  4. When looking up an item's value from a specific past snapshot, search through that item's timeline to find the most recent change that happened at or before that snapshot version.
  5. If no changes were made to that item by the requested snapshot version, fall back to the default starting value.

Code Implementation

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]

Big(O) Analysis

Time Complexity
O(log k) – When looking up an item's value at a specific snapshot, we perform a binary search through that item's history timeline containing k recorded changes. Rather than scanning every historical update linearly, the binary search divides the search space in half with each step. This process requires approximately log base 2 of k operations to find the most recent change at or before the requested snapshot version, which simplifies to O(log k).
Space Complexity
O(S + U) – The auxiliary space is driven by the data structures storing the timeline of changes for each index, where U is the total number of update operations and S is the initial length of the array. Each update appends a pair consisting of the snapshot version and the new value to the specific item's history list. Therefore, in the worst-case scenario where every update modifies a tracked index, the memory scales linearly with the total number of updates and the array size.

Edge Cases

Setting values for an index multiple times before taking any snapshot
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Binary search uses an upper bound or less-than-or-equal condition to correctly locate and return the value set at that exact snapshot.
0/1 completed