Snapshot Array in Python

PythonServer Side ProgrammingProgramming

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[0] = 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

Let us see the following implementation to get better understanding −

class SnapshotArray(object):
   def __init__(self, length):
      """
      :type length: int
      """
      self.current = 0
      self.arr = [[[0,0]] for i in range(length+1)]
   def set(self, index, val):
      """
      :type index: int
      :type val: int
      :rtype: None
      """
      temp = self.arr[index][-1]
      #print(temp)
      if temp[0] == self.current:
         self.arr[index][-1][1] = val
      else:
         self.arr[index].append([self.current,val])
   def snap(self):
      """
      :rtype: int
      """
      self.current+=1
      return self.current -1
   def get(self, index, snap_id):
      """
      :type index: int
      :type snap_id: int
      :rtype: int
      """
      temp = self.arr[index]
      low = 0
      high = len(temp)-1
      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]

Input

["SnapshotArray","set","snap","set","get"]
[[3],[0,5],[],[0,6],[0,0]]

Output

[null,null,0,null,5]
raja
Published on 17-Mar-2020 07:11:33
Advertisements