LeetCode 1146: Snapshot Array Solution

Master LeetCode problem 1146 (Snapshot Array), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1146. Snapshot Array

Problem Explanation

Explanation

To implement the SnapshotArray, we can use a list of dictionaries to store the values at each index for each snapshot. Whenever a snapshot is taken, we increment a counter to generate a new snapshot ID. When querying for a value at a specific index and snapshot ID, we retrieve the value from the corresponding snapshot.

  • SnapshotArray(int length): Initialize a list of dictionaries to store the values for each index at each snapshot.
  • set(index, val): Set the value at the given index to val in the latest snapshot.
  • snap(): Take a snapshot by incrementing the snapshot ID counter.
  • get(index, snap_id): Get the value at the given index from the specified snapshot ID.

Time complexity:

  • set(index, val): O(1)
  • snap(): O(1)
  • get(index, snap_id): O(1)

Space complexity: O(length * snapshots)

Solution Code

class SnapshotArray {
    List<Map<Integer, Integer>> snapshots;
    int snapId;

    public SnapshotArray(int length) {
        snapshots = new ArrayList<>();
        for (int i = 0; i < length; i++) {
            snapshots.add(new HashMap<>());
        }
        snapId = 0;
    }

    public void set(int index, int val) {
        snapshots.get(index).put(snapId, val);
    }

    public int snap() {
        return snapId++;
    }

    public int get(int index, int snap_id) {
        Map<Integer, Integer> snapshot = snapshots.get(index);
        while (snap_id >= 0 && !snapshot.containsKey(snap_id)) {
            snap_id--;
        }
        return snapshot.getOrDefault(snap_id, 0);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1146 (Snapshot Array)?

This page provides optimized solutions for LeetCode problem 1146 (Snapshot Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1146 (Snapshot Array)?

The time complexity for LeetCode 1146 (Snapshot Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1146 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1146 in Java, C++, or Python.

Back to LeetCode Solutions