Online Stock Span
Pattern: Monotonic stack
The span of today's price is 1 plus the spans of the earlier days it beats in a row. Keep a stack of (price, span) with prices decreasing; each new price absorbs every smaller-or-equal entry on top and adds their spans.
The problem
Build StockSpanner with next(price), which returns today's span: the number of days in a row, ending today, whose
price was at most today's. Prices 100, 80, 60, 70, 60, 75, 85 give spans 1, 1, 1, 2, 1, 4, 6.
Think first
- What stops a span going further back?
- If today beats yesterday, which days are covered for free?
- Do you need the days that were absorbed later?
Hints
Brute force, and why it fails
Walk back from today until a higher price: O(n) per call, O(n²) in total.
The key insight
Merge beaten days into one stack entry with their total span. The stack holds decreasing prices, and each day is pushed and popped once.
Dry run
| stack | (100,1) (80,1) (60,1) |
|---|
Prices 100, 80, 60: each is smaller than the top, so each span is 1.
The plan
next(price):
span = 1
while stack and top.price <= price: span += pop().span
push (price, span)
return span
Complexity
- Time
O(1) amortised per call- Space
O(n)
Each day's entry is pushed once and popped at most once.
Edge cases
- Increasing prices: spans 1, 2, 3, ….
- Decreasing prices: all 1.
- Equal prices are included in the span.
I've built my logic, show the code
Java
import java.util.*;
class StockSpanner {
private final Deque<int[]> st = new ArrayDeque<>(); // {price, span}, prices decreasing from bottom to top
public int next(int price) {
int span = 1;
while (!st.isEmpty() && st.peek()[0] <= price) span += st.pop()[1]; // absorb smaller-or-equal days
st.push(new int[]{price, span});
return span;
}
}C++
class StockSpanner {
public:
vector<pair<int, int>> st; // {price, span}, prices decreasing from bottom to top
int next(int price) {
int span = 1;
while (!st.empty() && st.back().first <= price) { span += st.back().second; st.pop_back(); } // absorb
st.push_back(make_pair(price, span));
return span;
}
};Python
class StockSpanner:
def __init__(self):
self.st = [] # (price, span), prices decreasing from bottom to top
def next(self, price: int) -> int:
span = 1
while self.st and self.st[-1][0] <= price:
span += self.st.pop()[1] # absorb smaller-or-equal days
self.st.append((price, span))
return spanCommon mistakes
- Using
<instead of<=, which stops at an equal price. - Storing indexes without spans and walking back anyway.