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];
}
};
Difficulty
and has an acceptance rate of about 37% (700k+ submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
- Design
- Hash Table
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
Other Solutions
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++ |
Videos
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
Extra
- 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