Problem 901

Abstract / Summary

Each day track how many consecutive days before the stock price was less than or equal to today's price.

Note

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

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;
    }
};
24 lines | 499 bytes | submitted September 12, 2023 | GitHub   5% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 69% (800k+ submissions).

Typical patterns to solve this problem:
  • Data Stream
  • Design
  • Monotonic Stack
  • Stack
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 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.

written by openai gpt

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.

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 = 6 | μ = 5.78 | σ = 1.66

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 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++
38 links | 24 authors | 9 languages

Videos

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

Similar Problems

1 similar problem

Solved On The Same Day

26 solutions   September 12, 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