Snapshot Array — LeetCode 1146 Python Solution
MediumDesignArrayHash TableBinary Search
- Problem
- #1146
- Pattern
- Binary Search
- Reading time
- 4 min
- Source
- leetcode.com
The 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.
Example
- Input
- ["SnapshotArray","set","snap","set","get"]
- Output
- [null,null,0,null,5]
- Explanation
- SnapshotArray snapshotArr = new SnapshotArray(3); // set the length to be 3
Python solution
Python
class SnapshotArray:
def __init__(self, length: int):
self.arr = [[] for _ in range(length)]
self.i = 0
def set(self, index: int, val: int) -> None:
self.arr[index].append((self.i, val))
def snap(self) -> int:
self.i += 1
return self.i - 1
def get(self, index: int, snap_id: int) -> int:
i = bisect_left(self.arr[index], (snap_id, inf)) - 1
return 0 if i < 0 else self.arr[index][i][1]
# Your SnapshotArray object will be instantiated and called as such:
# obj = SnapshotArray(length)
# obj.set(index,val)
# param_2 = obj.snap()
# param_3 = obj.get(index,snap_id)Complexity
| Measure | Complexity |
|---|---|
| Time | O(1) |
| Space | O(n) auxiliary |
Pattern: Binary Search
Halve the search space each step — over an array, or over the answer itself. LeetCode 1146. Snapshot Array is filed here because LeetCode tags it Binary Search, which is the vocabulary this hub collects.
The binary search guide has the Python template for the pattern and the 254 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1146. Snapshot Array?
- LeetCode 1146. Snapshot Array is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1146. Snapshot Array?
- The Python solution on this page runs in O(1).
- What is the space complexity of LeetCode 1146. Snapshot Array?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1146. Snapshot Array cover?
- LeetCode 1146. Snapshot Array is tagged Design, Array, Hash Table and Binary Search on LeetCode.