C++ 0901.cpp
class StockSpanner {
map<int, int, std::greater<int>> last;
int today;
public:
StockSpanner()
: last(),
today(0)
{
last[0] = 9999999;
}
int next(int price)
{
// std::greater => descending order => newest first
while (last.begin()->second <= price)
last.erase(last.begin());
today++;
int span = today - last.begin()->first;
last[today] = price;
return span;
}
};
Difficulty
and has an acceptance rate of about 69% (800k+ submissions).
Typical patterns to solve this problem:
- Data Stream
- Design
- Monotonic Stack
- Stack
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 StockSpanner class implements a data structure that, given a sequence of daily stock prices, can return the “span” of the current day's price - the number of consecutive days (including today) the price has been less than or equal to the current price. The implementation relies on a std::map ordered in descending key order to keep track of price entries keyed by the day index. Each call to next updates the internal state and computes the span in constant amortized time.
Core Data Members
The class maintains two private members:
std::map<int, int, std::greater<int>> last;
int today;
last stores pairs of (day, price) sorted by day in descending order, so the most recent day is always at last.begin(). The sentinel entry last[0] = 9999999 guarantees that the map is never empty and provides a convenient lower bound for span calculations. today tracks the current day index, starting from zero and incremented with each call to next.
Constructor
The constructor initializes the map and the day counter:
StockSpanner()
: last(),
today(0)
{
last[0] = 9999999;
}
The explicit initialization list sets today to zero. The sentinel entry with a very large price ensures that the while-loop in next always terminates, even when the incoming price exceeds all previously stored prices.
next Method - Step by Step
The next function processes a new price and returns its span.
Removing Dominated Entries
while (last.begin()->second <= price)
last.erase(last.begin());
Because the map is ordered with the newest day first, the loop examines the most recent entry. If that entry’s price is less than or equal to the new price, it cannot serve as a boundary for the span and is removed. The loop continues until it finds an entry with a higher price, which becomes the leftmost boundary for the current span.
Advancing the Day Counter
today++;
The day index is incremented to reflect the arrival of a new price.
Computing the Span
int span = today - last.begin()->first;
After the removal loop, last.begin()->first holds the day index of the nearest previous price that is strictly greater than the current price. Subtracting this index from the current day yields the number of consecutive days (including today) where the price has not been exceeded.
Recording the New Price
last[today] = price;
return span;
The new price is inserted with its day index, preserving the descending order invariant. The computed span is then returned to the caller.
Edge Cases Handled
When the incoming price is larger than every price seen so far, the removal loop erases all entries except the sentinel at day zero. The sentinel’s price of 9999999 is guaranteed to be larger than any realistic input, so the loop stops after clearing the map. The span calculation then becomes today - 0, which correctly yields the total number of days processed.
If the incoming price is equal to the most recent price, the loop removes that entry because the condition uses <=. This ensures that equal prices are treated as part of the same span, matching the definition that the span includes days with price less than or equal to the current price.
When the price is lower than the most recent price, the removal loop does not execute, leaving the map unchanged except for the insertion of the new entry. The span then becomes 1, reflecting that only the current day satisfies the “price ≤ current” condition.
Performance Optimizations
The choice of a std::map with a custom comparator (std::greater<int>) provides direct access to the most recent entry via begin(). This eliminates the need for additional data structures or reverse iterators. By erasing dominated entries in a tight loop, the algorithm maintains a monotonic stack-like property: each price is inserted once and removed at most once. Consequently, the total number of map operations across all calls to next is linear in the number of processed days, giving an amortized constant cost per call.
The sentinel entry eliminates the need for explicit empty-map checks before accessing begin(). This small constant-time guard simplifies the loop condition and avoids branching that could degrade cache performance.
Storing the day index as the map key rather than the price ensures that look-ups and deletions are based on the natural ordering of days, which aligns with the problem’s temporal nature and keeps the map balanced without extra bookkeeping.
ELI5 - Simplified Explanation
Imagine a magical notebook that keeps track of the height of a growing plant every single day. The notebook uses a special box called a map to store these measurements in a very specific way. When a new measurement comes in, the notebook looks at the previous entries starting from the earliest records. If the plant is taller today than it was on a previous day, the notebook crosses out that old, smaller measurement because it is no longer the most important one to remember. This keeps the notebook tidy and makes it easy to see how long ago the plant was last this short. After clearing out the old records, the notebook writes down today's day and how tall the plant is. By subtracting the day the plant was last taller than today from the current day, the notebook figures out the number of days the plant has been growing without a break. It is like keeping a diary that only holds onto the most useful clues to help solve a puzzle about growth.
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 | Rust | Go | TS | ||||
| LeetcodeHelp | C++ | Java | Python | |||||||
| Progiez | C++ | Java | Python | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| fpdjsns | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| sonugiri1043 | C++ | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| vthwang | Java | |||||||||
| wisdompeak | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| fpdjsns | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| sonugiri1043 | C++ | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| vthwang | Java | |||||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 739: Daily Temperatures
Solved On The Same Day
- problem 724: Find Pivot Index
- problem 872: Leaf-Similar Trees
- problem 933: Number of Recent Calls
- problem 1207: Unique Number of Occurrences
- problem 1732: Find the Highest Altitude
- problem 2215: Find the Difference of Two Arrays
- problem 328: Odd Even Linked List
- problem 443: String Compression
- problem 649: Dota2 Senate
- problem 735: Asteroid Collision
- problem 875: Koko Eating Bananas
- problem 1161: Maximum Level Sum of a Binary Tree
- problem 1268: Search Suggestions System
- problem 1282: Group the People Given the Group Size They Belong To
- problem 1372: Longest ZigZag Path in a Binary Tree
- problem 1448: Count Good Nodes in Binary Tree
- problem 1456: Maximum Number of Vowels in a Substring of Given Length
- problem 1493: Longest Subarray of 1's After Deleting One Element
- problem 1647: Minimum Deletions to Make Character Frequencies Unique
- problem 1657: Determine if Two Strings Are Close
- problem 1926: Nearest Exit from Entrance in Maze
- problem 2095: Delete the Middle Node of a Linked List
- problem 2130: Maximum Twin Sum of a Linked List
- problem 2352: Equal Row and Column Pairs
- problem 2390: Removing Stars From a String
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