Snapshot Array Problem
Snapshot Array Problem — ExecCode Medium DSA Practice
Solve the Snapshot Array problem on ExecCode. Free online medium DSA practice in Design. Write and run code in Java, C++, Python — no signup required to run.
Problem description
Description Implement a SnapshotArray that supports the following interface: SnapshotArray(int length) initializes an array-like data structure with the given length. Initially, each element equals 0. void set(index, val) sets the element at the given index to be equal to val. int snap() takes a snapshot of the array and returns the snapid: the total number of times we called snap() minus 1. int get(index, snapid) returns the value at the given index, at the time we took the snapshot with the given snapid Examples Example 1 Input: ["SnapshotArray","set","snap","set","get"] [[3],[0,5],[],[0,6],[0,0]] Output: [null,null,0,null,5] Explanation: SnapshotArray snapshotArr = new SnapshotArray(3); // set the length to be 3 snapshotArr.set(0,5); // Set array[0] = 5 snapshotArr.snap(); // Take a snapshot, return snapid = 0 snapshotArr.set(0,6); snapshotArr.get(0,0); // Get the value of array[0] with snapid = 0, return 5 Constraints 1 <= length <= 5 10^4 0 <= index < length 0 <= val <= 10^9 0 <= snapid <(the total number of times we call snap()) At most 5 10^4 calls will be made to set, snap, and get.
Examples
Input {"data": "[\"SnapshotArray\",\"set\",\"snap\",\"set\",\"get\"]\n[[3],[0,5],[],[0,6],[0,0]]"}; Output [null,null,0,null,5]. Input {"data": "SnapshotArray(3); set(0,5); snap(); set(0,6); get(0,0)"}; Output [null,null,0,null,5]. Input {"data": "SnapshotArray(4); set(1,7); snap(); set(1,9); set(2,5); snap(); get(1,0); get(1,1); get(2,1)"}; Output [null,null,0,null,null,1,7,9,5]
Constraints
1 <= length <= 5 10^4 0 <= index < length 0 <= val <= 10^9 0 <= snap_id <(the total number of times we call snap()) At most 5 10^4 calls will be made to set, snap, and get.
Practice Snapshot Array free on ExecCode. Browse DSA problems, topic map, and placement guides.