Skip to main content

Snapshot Array

MediumPremium

Implement a SnapshotArray class: an array of integers that can save snapshots of itself and read values from any earlier snapshot.

  • SnapshotArray(length) creates an array of length elements, all starting at 0.
  • set(index, val) sets the element at index to val.
  • snap() takes a snapshot and returns its id. The first snapshot has id 0, and each call returns the previous id plus one.
  • get(index, snap_id) returns the value at index at the moment snapshot snap_id was taken.

The tests run a sequence of operations on one array and check the values returned by every snap and get call, in order.

Example 1

Input: ["SnapshotArray", "set", "snap", "set", "get"] [[3], [0, 5], [], [0, 6], [0, 0]] Output: [0, 5]

The array starts as [0, 0, 0]. Setting index 0 to 5 and taking a snapshot returns id 0. Setting index 0 to 6 afterward doesn't change snapshot 0, so get(0, 0) returns 5.

Example 2

Input: ["SnapshotArray", "snap", "get", "set", "snap", "get"] [[2], [], [1, 0], [1, 4], [], [1, 1]] Output: [0, 0, 1, 4]

Index 1 is still 0 in snapshot 0. It's set to 4 before snapshot 1 is taken, so snapshot 1 sees 4.

Constraints

  • 1 <= length <= 50000
  • 0 <= index < length and 0 <= val <= 10^9
  • get is only called with a snap_id that has already been taken.
  • At most 50000 calls are made in total.