Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Snapshot Array in Python
A Snapshot Array is a data structure that allows you to take snapshots of an array at different points in time and retrieve values from those snapshots. This is useful when you need to track the history of changes to array elements.
Interface Requirements
The SnapshotArray must support these operations:
SnapshotArray(int length)− Initialize array with given length, all elements start as 0set(index, val)− Set element at given index to valsnap()− Take a snapshot and return snapshot ID (starts from 0)get(index, snap_id)− Get value at index from a specific snapshot
Algorithm Approach
The key insight is to store version history for each array position using a 2D structure:
Each array index stores a list of
[snapshot_id, value]pairsUse binary search to efficiently find the correct value for any snapshot
Only store changes when values are modified
Implementation
class SnapshotArray:
def __init__(self, length):
self.current = 0
# Each index stores [[snapshot_id, value]] pairs
self.arr = [[[0, 0]] for i in range(length)]
def set(self, index, val):
temp = self.arr[index][-1]
# If current snapshot already has a value, update it
if temp[0] == self.current:
self.arr[index][-1][1] = val
else:
# Add new snapshot entry
self.arr[index].append([self.current, val])
def snap(self):
self.current += 1
return self.current - 1
def get(self, index, snap_id):
temp = self.arr[index]
low = 0
high = len(temp) - 1
# Binary search for the correct snapshot
while low < high:
mid = low + (high - low + 1) // 2
if temp[mid][0] <= snap_id:
low = mid
else:
high = mid - 1
return temp[low][1]
# Example usage
snapshot_arr = SnapshotArray(3)
snapshot_arr.set(0, 5)
print(snapshot_arr.snap()) # Takes first snapshot
snapshot_arr.set(0, 6)
print(snapshot_arr.get(0, 0)) # Get value from snapshot 0
0 5
How It Works
Let's trace through the example:
SnapshotArray(3)− Creates array with 3 positions, each initialized as[[[0, 0]]]set(0, 5)− Sets index 0 to value 5 in current snapshot (0)snap()− Takes snapshot, returns ID 0, increments current to 1set(0, 6)− Sets index 0 to value 6 in current snapshot (1)get(0, 0)− Retrieves value at index 0 from snapshot 0, returns 5
Time Complexity
| Operation | Time Complexity | Description |
|---|---|---|
__init__ |
O(length) | Initialize array structure |
set |
O(1) | Append or update last entry |
snap |
O(1) | Increment counter |
get |
O(log S) | Binary search through S snapshots |
Conclusion
The SnapshotArray uses version control principles to efficiently track array changes over time. Binary search ensures fast retrieval from any snapshot, making it suitable for applications requiring historical data access.
