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.

Open the playground โ†’

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.

Inputprices arrive as 100, 80, 60, 70, 60, 75, 85
Output1, 1, 1, 2, 1, 4, 6

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.

Brute force first: Walking backwards from today until a higher price appears is O(n) per day, so O(nยฒ) for a rising market.

Step-by-step approach

  1. Keep a stack of pairs (price, span).
  2. For a new price, start with span = 1.
  3. While the stack's top price is <= price, pop it and add its span to span.
  4. Push (price, span) and return span.

Python solution

PYTHON 3tested
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 span

Complexity

TimeO(1) amortised per call
SpaceO(n)

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

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.