1146. Snapshot Array

https://leetcode.com/problems/snapshot-array/description/


class SnapshotArray {
    HashMap<Integer, HashMap<Integer, Integer>> snap = new HashMap<Integer, HashMap<Integer, Integer>>();
    int snaped = -1;
    public SnapshotArray(int length) {
        snaped++;
    }
    
    public void set(int index, int val) {
        if(!snap.containsKey(index)) {
            snap.put(index, new HashMap<Integer, Integer>());
        }
        snap.get(index).put(snaped, val);
    }
    
    public int snap() {
        snaped++;
        return snaped-1;
    }
    
    public int get(int index, int snap_id) {
        if(!snap.containsKey(index))
            return 0;
        
        if (snap.get(index).containsKey(snap_id)) {
            return (Integer)snap.get(index).get(snap_id);
        }
        int prev = -1;
        for (Map.Entry<Integer,Integer> entry : snap.get(index).entrySet()) {
            int snapId = entry.getKey();
            if(snapId < snap_id) {
                if (prev == -1) 
                    prev = snapId;
                else if (snapId > prev) {
                    prev = snapId;
                }
            }
        }
        return snap.get(index).containsKey(prev) ? (Integer)snap.get(index).get(prev) : 0;
    }
}

Here’s a breakdown of the code:

  1. The class SnapshotArray has a member variable snap which is a HashMap. This HashMap has an Integer key (representing the index) and a nested HashMap as its value. The nested HashMap has an Integer key (representing the snapshot ID) and an Integer value (representing the value at that index and snapshot).
  2. The variable snaped is an integer that keeps track of the current snapshot ID. It is initialized to -1.
  3. The constructor SnapshotArray(int length) initializes the snaped variable by incrementing it, indicating the creation of a new snapshot.
  4. The method set(int index, int val) is used to set the value at a specific index. It first checks if the index exists in the snap HashMap. If not, it creates a new nested HashMap for that index. It then adds the value at the current snapshot ID to the nested HashMap.
  5. The method snap() is used to create a new snapshot. It increments the snaped variable and returns the previous snapshot ID.
  6. The method get(int index, int snap_id) is used to retrieve the value at a specific index and snapshot ID. It first checks if the index exists in the snap HashMap. If not, it returns 0. If the index exists, it iterates over the entries of the nested HashMap for that index. It finds the latest snapshot ID that is less than the provided snap_id. It then retrieves the value associated with that snapshot ID from the nested HashMap. If no such snapshot ID is found, it returns 0.

Related Post