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:
-
newSnapshotArray(length)
: This property initializes and returns a data structure withlength
number of indexes. Initially, the value at each index is0
. -
Set(idx,val)
: This property sets the value at a given indexidx
to val. -
Snapshot()
: This property takes no parameters and returns thesnapshotId
.snapshotId
is the number of times that thesnapshot()
function was called minus1
. -
Get(idx,snapid)
function returns the value at the indexidx
with the givensnapshotId
.
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 Set(idx,val)
function.
snapshotArr = NewSnapshotArray(3)
snapshotArr.Set(0,4)
snapshotArr.Snapshot()
snapshotArr.Get(0,0)
snapshotArr.Set(1,6)
snapshotArr.Snapshot()
snapshotArr.Get(1,1)
Output
The output will be an integer. We will receive an output by calling the Get(idx,snapshotId)
function. For example, we will get the following output after calling the Get(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 with the newSnapshotArray(length)
, Set(idx,val)
, Snapshot()
, and Get(idx,snapid)
functions:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.