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 Snapshot
with the following properties:
-
new(length)
: This property initializes 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. -
snap()
: This property takes no parameters and returns thesnapid
.snapid
is the number of times that thesnap()
function was called minus1
. -
get(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 set(idx,val)
function.
let mut snapshot_arr: Snapshot = Snapshot::new(3);
snapshot_arr.set(0,4);
snapshot_arr.snap();
snapshot_arr.get(0,0);
snapshot_arr.set(1,6);
snapshot_arr.snap();
snapshot_arr.get(1,1);
Output
The output will be an integer. We will receive an output by calling the get(idx,snapid)
function. For example, we will get the following output after calling the get(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:
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.