# Snapshot Array in Python

Suppose we have to Implement a SnapshotArray that supports the following interfaces −

• SnapshotArray(int length) this will initialize the array-like data structure with the given length. Initially, each element equals 0.

• set(index, val) this will sets the element at the given index to be equal to val.

• snap() will take a snapshot of the array and returns the snap_id: the total number of times we called snap() minus 1.

• get(index, snap_id) this will return the value at the given index, at the time we took the snapshot with the given snap_id

So if the array size is 2, it is set using [0, 5], after that we take a snap, it will return 0, then set using [0, 6], and get(0, 0), this will return 5.

To solve this, we will follow these steps −

• The initialize method will be like −

• current := 0

• arr := an array of length + 1 number of 2d arrays [[0, 0]]

• The set() method will be like −

• temp := last element of arr[index]

• if temp = current, then element of index 1 from the last element of arr[index] := val

• otherwise insert [current, val] into arr[index]

• The snap() method will be like−

• increase current by 1, return one less than count

• The get() method will be like −

• temp := arr[index], low := 0, high := length of temp – 1

• while low < high

• mid := low + (high – low) / 2

• if temp[mid, 0] <= snap_id, then low := mid, otherwise high := mid – 1

• return temp[low, 1]

## Example(Python)

Let us see the following implementation to get better understanding −

Live Demo

class SnapshotArray(object):
def __init__(self, length):
self.current = 0
self.arr = [[[0,0]] for i in range(length+1)]
def set(self, index, val):
temp = self.arr[index][-1]
#print(temp)
if temp == self.current:
self.arr[index][-1] = val
else:
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
while low < high:
mid = low + (high - low+1 )//2
if temp[mid]<=snap_id:
low = mid
else:
high = mid -1
return temp[low]
ob = SnapshotArray(3)
ob.set(0,5)
print(ob.snap())
ob.set(0,6)
print(ob.get(0,0))

## Input

Initialize the array using 3, then call set(0,5), snap(), set(0,6), get(0, 0)

## Output

0
5

Updated on: 30-Apr-2020

435 Views 