1146. Snapshot Array

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 snap_id: the total number of times we called snap() minus 1.
  • int get(index, snap_id) returns the value at the given index, at the time we took the snapshot with the given snap_id

 

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 snap_id = 0
snapshotArr.set(0,6);
snapshotArr.get(0,0);  // Get the value of array[0] with snap_id = 0, return 5

 

Constraints:

  • 1 <= length <= 50000
  • At most 50000 calls will be made to set, snap, and get.
  • 0 <= index < length
  • 0 <= snap_id < (the total number of times we call snap())
  • 0 <= val <= 10^9

Rust Solution

type Pair = (usize, i32);

struct SnapshotArray {
    size: usize,
    data: Vec<Vec<Pair>>,
    snap_id: usize,
}

impl SnapshotArray {
    fn new(length: i32) -> Self {
        let size = length as usize;
        let data = vec![vec![(0, 0)]; size];
        let snap_id = 0;
        SnapshotArray {
            size,
            data,
            snap_id,
        }
    }

    fn set(&mut self, index: i32, val: i32) {
        let i = index as usize;
        if let Some(last) = self.data[i].pop() {
            if last.0 != self.snap_id {
                self.data[i].push(last);
            }
        }
        self.data[i].push((self.snap_id, val));
    }

    fn snap(&mut self) -> i32 {
        self.snap_id += 1;
        (self.snap_id - 1) as i32
    }

    fn get(&self, index: i32, snap_id: i32) -> i32 {
        let i = index as usize;
        let snap_id = snap_id as usize;
        match self.data[i].binary_search_by_key(&snap_id, |p| p.0) {
            Ok(j) => self.data[i][j].1,
            Err(j) => self.data[i][j - 1].1,
        }
    }
}

#[test]
fn test() {
    let mut obj = SnapshotArray::new(3);
    obj.set(0, 5);
    assert_eq!(obj.snap(), 0);
    obj.set(0, 6);
    assert_eq!(obj.get(0, 0), 5);
}

Having problems with this solution? Click here to submit an issue on github.