DIY: Snapshot Array

Solve the interview question "Snapshot Array" in this lesson.

Problem statement

In this challenge, you have to implement a SnapshotArray with the following properties:

  • SnapshotArray(length): This property initializes a data structure with length number of indexes. Initially, the value at each index is 0.

  • setValue(idx, val): This property sets the value at a given index idx to val.

  • snapshot(): This property takes no parameters and returns the snapshotId. snapshotId is the number of times that the snapshot() function was called minus 1.

  • getValue(idx, snapshotId) function returns the value at the index idx with the given snapshotId.

Input

The input will be two integers, that is an index and a value. We can set the value of the index idx, using the setValue(idx, val) function.

snapshotArr = SnapshotArray(3)
snapshotArr.setValue(0,4)
snapshotArr.snapshot()
snapshotArr.getValue(0,0)
snapshotArr.setValue(1,6) 
snapshotArr.snapshot()
snapshotArr.getValue(1,1)

Output

The output will be an integer. We will receive an output by calling the getValue(idx, snapshotId) function. For example, we will get the following output after calling the getValue(idx, snapshotId) function on the input given above:

4
6

Coding exercise

Using the skeleton code given below, you need to implement the SnapshotArray class:

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.