Leetcode #901: Online Stock Span
In this guide, we solve Leetcode #901 Online Stock Span in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Design an algorithm that collects daily price quotes for some stock and returns the span of that stock's price for the current day. The span of the stock's price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Stack, Design, Data Stream, Monotonic Stack
Intuition
We need the next greater or smaller element efficiently, which is exactly what a monotonic stack offers.
Each element is pushed and popped at most once, yielding a linear-time scan.
Approach
Maintain a stack that is either increasing or decreasing, depending on the query.
When the invariant is broken, pop and resolve answers for those indices.
Steps:
- Scan elements once.
- Pop while the monotonic condition is violated.
- Use stack indices to update answers.
Example
Input
["StockSpanner", "next", "next", "next", "next", "next", "next", "next"]
[[], [100], [80], [60], [70], [60], [75], [85]]
Output
[null, 1, 1, 1, 2, 1, 4, 6]
Explanation
StockSpanner stockSpanner = new StockSpanner();
stockSpanner.next(100); // return 1
stockSpanner.next(80); // return 1
stockSpanner.next(60); // return 1
stockSpanner.next(70); // return 2
stockSpanner.next(60); // return 1
stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price.
stockSpanner.next(85); // return 6
Python Solution
class StockSpanner:
def __init__(self):
self.stk = []
def next(self, price: int) -> int:
cnt = 1
while self.stk and self.stk[-1][0] <= price:
cnt += self.stk.pop()[1]
self.stk.append((price, cnt))
return cnt
# Your StockSpanner object will be instantiated and called as such:
# obj = StockSpanner()
# param_1 = obj.next(price)
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.