Algo-Sim › Stacks & Monotonic Stack
Online Stock Span
Medium · Stacks & Monotonic Stack · step through it in Java, Python and C++ on your own input
Each call next(price) returns how many consecutive days, ending today, the price was less than or equal to today's.
Problem
Design a class that receives one stock price per day through next(price). Each call returns today's span: the number of consecutive days ending today (today included) on which the price was less than or equal to today's price.
Constraints
- 1 ≤ price ≤ 10⁵
- At most 10⁴ calls to next
- Each call should be amortised O(1)
Edge cases to test
- Strictly rising prices: spans grow by one
- Equal prices count toward the span
- The first call returns 1
Follow-up questions
- Why store (price, span) pairs?
- Popping a smaller price adds its span, so each price is pushed and popped once: O(1) amortized per call.
- What if you need spans over a window only?
- Keep indices instead of spans and cap the answer at the window length.
Solution
Java
class StockSpanner {
private final Deque<int[]> stack = new ArrayDeque<>();
public int next(int price) {
int span = 1;
while (!stack.isEmpty() && stack.peek()[0] <= price) {
span += stack.pop()[1];
}
stack.push(new int[] { price, span });
return span;
}
}Python
class StockSpanner:
def __init__(self):
self.stack = []
def next(self, price):
span = 1
while self.stack and self.stack[-1][0] <= price:
span += self.stack.pop()[1]
self.stack.append((price, span))
return spanC++
#include <bits/stdc++.h>
using namespace std;
class StockSpanner {
public:
deque<vector<int>> stack = {};
int next(int price) {
int span = 1;
while (!stack.empty() && stack.back()[0] <= price) {
span += stack.back()[1];
stack.pop_back();
}
stack.push_back(vector<int>{price, span});
return span;
}
};
More Stacks & Monotonic Stack problems
- Valid Parentheses (Easy)
- Implement Queue using Stacks (Easy)
- Evaluate Reverse Polish Notation (Medium)
- Basic Calculator II (Medium)
- Basic Calculator (Hard)
- Decode String (Medium)
- Asteroid Collision (Medium)
- Next Greater Element (Easy)
- Daily Temperatures (Medium)
- Remove K Digits (Medium)
- Car Fleet (Medium)
- Largest Rectangle in Histogram (Hard)
- Maximal Rectangle (Hard)
- Sliding Window Maximum (Hard)