Coding interview problems โบ Stack & Monotonic Stack
๐ Stack & Monotonic Stack Medium
Online Stock Span
Online Stock Span explained: keep a monotonic stack of (price, span) pairs and merge smaller days into each new one, amortised O(1). Tested Python, live visual.
Also searched as: stock span problem ยท stock span using stack ยท previous greater element
Try it live Free
Stacks & the Monotonic Stack
Step through the monotonic stack mode, where stock-span is one of the patterns: smaller entries pop the moment a bigger price arrives, and today's span grows by what they covered.
The problem
Prices of a stock arrive one day at a time. For each new price, return its span: the number of consecutive days, ending today and going backwards, on which the price was less than or equal to today's price. Today counts as one day.
75 covers 75, 60, 70, 60; 85 covers everything back to 80.
The key insight
When a higher price arrives, the smaller prices before it can never stop a future span: anything that would reach them reaches today first. So fold them into today. Keep a stack of (price, span) pairs with strictly decreasing prices; pop every pair with price at most today's and add its span to today's.
Step-by-step approach
- Keep a stack of pairs
(price, span). - For a new
price, start withspan = 1. - While the stack's top price is
<= price, pop it and add its span tospan. - Push
(price, span)and returnspan.
Python solution
class StockSpanner:
def __init__(self):
self.stack = [] # (price, span), prices decreasing
def next(self, price):
span = 1
while self.stack and self.stack[-1][0] <= price:
span += self.stack.pop()[1] # absorb the days that price covered
self.stack.append((price, span))
return spanComplexity
Each price is pushed once and popped at most once over all calls, so n calls cost O(n) total. A single call can still pop many entries.
Common mistakes
- Popping entries but forgetting to add their spans, so a span only counts the entries directly popped instead of all the days they covered.
- Using
<instead of<=, which stops the span at an equal price even though equal prices count. - Storing every price and rescanning the history on each call, which is the O(nยฒ) brute force in disguise.
Frequently asked questions
What is the time and space complexity of the stock span problem?
Each call is amortised O(1), so n prices cost O(n) in total. The stack uses O(n) space in the worst case, a steadily falling price.
How is stock span related to the previous greater element?
The span of day i is i minus the index of the previous strictly greater price. The stack version computes exactly that without storing indices.
Can I solve the offline version with an array of prices?
Yes. Scan the array with a stack of indices; after popping smaller-or-equal prices, the span is i minus the index on top, or i + 1 if the stack is empty.
Why is this called online?
Prices arrive one at a time and each answer must be returned before the next price is known, so you cannot look ahead.
Preparing for placements?
Take the 2-minute readiness check to find your weak patterns, then follow the placement path from DSA core to system design.
All coding interview problems More Stack & Monotonic Stack Stacks & the Monotonic Stack lab Placement prep guides
Problem statements on this site are written in our own words. Problem names are the common names used across interview-prep communities; BitBootcamp is an independent learning platform and is not affiliated with LeetCode or any company that asks these questions.