#1146
Snapshot Array
MediumArrayHash TableBinary SearchDesignHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n * s) where s is the number of snapshots | O(n * s) where s is the number of snapshots |
💡
Intuition
Time O(n)Space O(n * s) where s is the number of snapshots
The optimal approach uses a list of dictionaries to store the values at each index along with their corresponding snap_ids. This allows for efficient retrieval without needing to copy the entire array for each snapshot.
⚙️
Algorithm
4 steps- 1Step 1: Initialize an array of dictionaries to store values and their corresponding snap_ids.
- 2Step 2: For the 'set' operation, update the value at the specified index with the current snap_id.
- 3Step 3: For the 'snap' operation, increment the snap_id counter and return the current snap_id.
- 4Step 4: For the 'get' operation, retrieve the value from the dictionary for the specified index, using the largest snap_id that is less than or equal to the requested snap_id.
solution.py20 lines
1class SnapshotArray:
2 def __init__(self, length: int):
3 self.data = [{} for _ in range(length)]
4 self.snap_id = 0
5
6 def set(self, index: int, val: int) -> None:
7 self.data[index][self.snap_id] = val
8
9 def snap(self) -> int:
10 self.snap_id += 1
11 return self.snap_id - 1
12
13 def get(self, index: int, snap_id: int) -> int:
14 if snap_id in self.data[index]:
15 return self.data[index][snap_id]
16 # Find the largest snap_id less than the requested one
17 for i in range(snap_id, -1, -1):
18 if i in self.data[index]:
19 return self.data[index][i]
20 return 0ℹ
Complexity note: The time complexity for 'set' and 'snap' operations is O(1), while 'get' can take O(n) in the worst case if we have to search through all previous snapshots. However, this is efficient given the constraints.
- 1Using a list of dictionaries allows for efficient storage of values with their corresponding snap_ids.
- 2The optimal solution avoids unnecessary copying of the entire array, saving both time and space.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.