Online Stock Span (LeetCode 901): Solution and Explanation
Prices arrive one day at a time. For each new price, return its span: how many consecutive days, ending today and counting backward, had a price less than or equal to today's. You implement a StockSpanner class whose next(price) method returns that span.
Intuition
The direct approach walks backward from today until it finds a higher price. On a long rising stretch that walk covers almost every earlier day, so a stream of n prices costs O(n²).
The saving comes from noticing that spans nest. Suppose yesterday's price is at most today's. Every day inside yesterday's span was at most yesterday's price, so it is also at most today's price. You can jump over that whole block in one step by adding yesterday's span, instead of revisiting each day.
Once a day has been folded into a later day with an equal or higher price, it can never stop a future walk: the later day is closer to the future and at least as high. So that day can be thrown away for good. What remains is a stack of days whose prices strictly fall from bottom to top, each stored with the span it covers.
Each price is pushed once and popped at most once, so even though a single call can pop many entries, the total work over the whole stream is linear.
Approach: Monotonic stack of (price, span)
- Keep a stack of
(price, span)pairs. It starts empty. - In
next(price), setspan = 1to count today. - While the stack is not empty and its top price is less than or equal to
price, pop the top and add its span tospan. - Push
(price, span)so later days can absorb today's block in one step. - Return
span.
Step-by-step example
next calls with 100, 80, 60, 70, 60, 75, 85
- next(100): the stack is empty, so the span is 1. Push (100, 1).
- next(80): the top 100 is higher, so the span is 1. Push (80, 1).
- next(60): the top 80 is higher, so the span is 1. Push (60, 1).
- next(70): pop (60, 1), span becomes 2. The top 80 is higher, so push (70, 2) and return 2.
- next(60): the top 70 is higher, so the span is 1. Push (60, 1).
- next(75): pop (60, 1) for span 2, then pop (70, 2) for span 4. The top 80 is higher, so push (75, 4) and return 4.
- next(85): pop (75, 4) for span 5, then pop (80, 1) for span 6. The top 100 is higher, so push (85, 6) and return 6. The outputs are [null,1,1,1,2,1,4,6].
Code: Python, Java, C++
1class StockSpanner:
2 def __init__(self):
3 self.stack = []
4
5 def next(self, price: int) -> int:
6 span = 1
7 while self.stack and self.stack[-1][0] <= price:
8 span += self.stack.pop()[1]
9 self.stack.append((price, span))
10 return span1class StockSpanner {
2 private Deque<int[]> stack;
3
4 public StockSpanner() {
5 stack = new ArrayDeque<>();
6 }
7
8 public int next(int price) {
9 int span = 1;
10 while (!stack.isEmpty() && stack.peek()[0] <= price) {
11 span += stack.pop()[1];
12 }
13 stack.push(new int[]{price, span});
14 return span;
15 }
16}1class StockSpanner {
2 stack<pair<int, int>> st;
3
4public:
5 StockSpanner() {}
6
7 int next(int price) {
8 int span = 1;
9 while (!st.empty() && st.top().first <= price) {
10 span += st.top().second;
11 st.pop();
12 }
13 st.push({price, span});
14 return span;
15 }
16};Time and space complexity
O(1) amortized per call
A single call can pop many entries, but every price is pushed once and popped at most once over the whole stream, so n calls take O(n) in total.
O(n)
When prices keep falling, nothing is ever popped and the stack holds every price.
Other approaches
Walk backward over all prices (time O(n) per call, space O(n))
Store every price in a list and, for each call, scan backward until a higher price appears. It is easy to get right but costs O(n) per call on rising prices, O(n²) overall.
Stack of indices with a price list (time O(1) amortized per call, space O(n))
Store all prices in a list and keep a stack of indices of the falling prices. The span is today's index minus the index left on top after popping (or index + 1 if the stack is empty). It is the same monotonic stack, just storing positions instead of spans.
Common mistakes
- Popping only while the top is strictly less than today's price. Equal prices also count toward the span, so the condition must be
<=. - Pushing
(price, 1)instead of the accumulated span. The popped days are gone from the stack, so the new entry has to carry their count. - Resetting the stack between calls. The object must remember earlier days, so the stack lives on the instance, not inside
next. - Assuming one call is O(1). A single call can pop many entries; only the amortized cost over all calls is constant.
Frequently asked questions
Why is it safe to pop a day from the stack forever?
A popped day has a price at most today's price and sits before today. Any future walk that reaches it would have to pass today first, and today is at least as high, so today already accounts for it through its stored span.
Why does the stack keep strictly falling prices?
Before pushing today's price, every entry with a price less than or equal to it is popped. So whatever is left below it is strictly higher, and that holds after every push.
Is this the same idea as Daily Temperatures?
Yes. Both use a monotonic stack to find the nearest higher value on one side. Daily Temperatures looks forward for a warmer day, while Stock Span looks backward and counts how many days it covers.
What is the time complexity of Online Stock Span?
O(1) amortized per call to next, O(n) for n calls in total, with O(n) space for the stack.