Problem 1146

Abstract / Summary

Implement a list that supports setting values and taking snapshots to retrieve past versions.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 1146.cpp

class SnapshotArray {
    vector<vector<int>> when;
    vector<vector<int>> what;
    int timestamp;

public:
    SnapshotArray(int length) {
        when.resize(length);
        what.resize(length);
        timestamp = 0;
    }

    void set(int index, int val) {
        when[index].push_back(timestamp);
        what[index].push_back(val);
    }

    int snap() {
        return timestamp++;
    }

    int get(int index, int snap_id) {
        auto& bucket = when[index];
        auto i = upper_bound(bucket.begin(), bucket.end(), snap_id);

        if (i == bucket.begin())
            return 0;

        i--;
        auto pos = i - bucket.begin();
        return what[index][pos];
    }
};
33 lines | 729 bytes | submitted August 7, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 37% (700k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
  • Design
  • Hash Table
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The presented class implements a mutable array that can capture its state at discrete moments, called snapshots, and later retrieve the value of any element as it existed in a particular snapshot. Internally the design stores, for each index, a chronological list of timestamps (when) and the corresponding values (what). A global counter timestamp serves both as the identifier for the next snapshot and as the logical time marker for updates.

Core Construction

The constructor receives the desired length of the array. It allocates two parallel vectors of vectors, one for timestamps and one for values, each sized to the length of the logical array. The timestamp counter is initialized to zero, establishing the baseline snapshot identifier.

SnapshotArray(int length) {
    when.resize(length);
    what.resize(length);
    timestamp = 0;
}

Recording a Value

The set method records a new value for a given index. It appends the current timestamp to the when list for that index and stores the supplied value in the matching position of the what list. Because the timestamp is not incremented until a snapshot is taken, multiple set calls before a snap share the same timestamp, effectively coalescing updates that belong to the same logical snapshot.

void set(int index, int val) {
    when[index].push_back(timestamp);
    what[index].push_back(val);
}

Capturing a Snapshot

Calling snap returns the identifier of the snapshot that represents the state of the array at that moment. The method simply returns the current timestamp and then increments it, preparing a fresh identifier for subsequent updates. This approach guarantees that snapshot identifiers are consecutive integers starting from zero.

int snap() {
    return timestamp++;
}

Retrieving a Historical Value

The get method fetches the value of an element as it existed in a specific snapshot. It first obtains a reference to the timestamp list for the requested index. Using upper_bound, it locates the first stored timestamp that exceeds the requested snapshot identifier. If the iterator points to the beginning of the list, it means no update has been recorded for that index up to the requested snapshot, and the method returns the default value 0. Otherwise, the iterator is moved one step back to point at the greatest timestamp that does not exceed the snapshot identifier. The position of this timestamp within the list is then used to index into the parallel what list, yielding the stored value.

int get(int index, int snap_id) {
    auto& bucket = when[index];
    auto i = upper_bound(bucket.begin(), bucket.end(), snap_id);

    if (i == bucket.begin())
        return 0;

    i--;
    auto pos = i - bucket.begin();
    return what[index][pos];
}

Edge Cases Handled

When a get request targets a snapshot that precedes any recorded update for the specified index, the upper_bound call returns an iterator equal to bucket.begin(). The subsequent check detects this situation and returns the default value 0, correctly representing the initial state of the array before any modifications.

If multiple set operations occur before a snap, each call records the same timestamp, so the most recent value for that timestamp will be the one retrieved later. The binary search performed by upper_bound naturally selects the last occurrence that does not exceed the snapshot identifier, ensuring the correct value is returned even when several updates share the same timestamp.

When snap is invoked without any preceding set calls, the timestamp is still incremented and returned. Subsequent get calls for that snapshot will encounter empty timestamp vectors for all indices, causing the early-return path to produce 0, which matches the expected behavior of an untouched array.

Performance Optimizations

The design avoids copying the entire array for each snapshot. Instead, it stores only the points in time when a particular index changes, resulting in a sparse representation that scales with the number of updates rather than the product of array length and snapshot count.

Retrieval leverages binary search (upper_bound) on the per-index timestamp vector, providing logarithmic lookup time relative to the number of updates for that index. This targeted search eliminates the need to scan unrelated indices or earlier snapshots.

Appending timestamps and values in set is an amortized constant-time operation because the underlying vectors grow geometrically, minimizing reallocations.

The global timestamp counter is a simple integer that increments monotonically, allowing snapshot identifiers to be generated without additional bookkeeping or synchronization overhead.

Interaction Flow

A typical usage pattern proceeds as follows: an instance is created with a fixed length; a series of set calls record changes; a snap call captures the current logical state and yields an identifier; later, get calls retrieve values for any index at any previously captured snapshot identifier. The internal structures maintain the necessary history to answer these queries efficiently while keeping memory usage proportional to actual modifications.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a row of magic toy boxes numbered from zero to as many as you like. This code is like a special camera that takes a picture of all these toy boxes whenever you want.

When you use the set function, you are putting a new toy into a specific box. The code writes down the number of the current picture on that toy so it knows exactly when you put it there.

The snap function is the button on the camera. Every time you push it, the camera clicks and adds one to the picture count. This way, every toy you put away after this moment will belong to a higher-numbered picture.

The get function is like looking through an album to see what was in a specific box at a specific time. It looks for the picture number you asked for and checks the boxes to find the toy that was there exactly when that picture was taken. If you look for a picture that was taken before you put anything in the box, the code just tells you there is nothing there yet.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.04 | σ = 0.92

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Go TS
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
Dijkstra-Edu Java
DimitrisJim JS
everthis JS
fsq C++
JoshCrozier JS
lkwq007 Python
martianoff Scala
muhammadfarhankt Go
suxrobGM C#
varunu28 Java
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
Dijkstra-Edu Java
DimitrisJim JavaScript
everthis JavaScript
fsq C++
JoshCrozier JavaScript
lkwq007 Python
martianoff Scala
muhammadfarhankt Go
suxrobGM C#
varunu28 Java
wisdompeak C++
28 links | 17 authors | 8 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

40 easy 30 medium 1 hard
72 solutions   August 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality