DIY: Snapshot Array
Solve the interview question "Snapshot Array" in this lesson.
We'll cover the following
Problem statement
In this challenge, you have to implement a SnapShotArray
with the following properties:
-
SnapShotArray(length)
: This property initializes a data structure withlength
number of indexes. Initially, the value at each index is0
. -
setValue(idx,val)
: This property sets the value at a given indexidx
to val. -
snapShot()
: This property takes no parameters and returns thesnapId
.snapId
is the number of times that thesnapshot()
function was called minus1
. -
getValue(idx,snapId)
function returns the value at the indexidx
with the givensnapId
.
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,snapId)
function. For example, we will get the following output after calling the getValue(idx,snapId)
function on the input given above:
4
6
Coding exercise
Using the skeleton code given below, you need to implement the SnapShotArray
class with the SnapShotArray(length)
, setValue(idx,val)
, snapShot()
, and getValue(idx,snapId)
functions:
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.