Online Stock Span

MediumMonotonic Stack · Design🧩 Monotonic StackLeetCode #901 ↗Updated

Problem

Build a class StockSpanner that receives one daily stock price at a time through next(price). Each call must return today's span: the length of the longest run of consecutive days ending today (today included) on which the price was less than or equal to today's price.
Inputnext: 100, 80, 60, 70, 60, 75, 85Output1, 1, 1, 2, 1, 4, 6
Inputnext: 5, 5, 5Output1, 2, 3

1 ≤ price ≤ 105  ·  at most 104 calls to next

Try it yourself

Java
class StockSpanner {
    public StockSpanner() {
        
    }

    public int next(int price) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
A day that is beaten by a later, higher-or-equal price can never stop a future span — the later day blocks it first. So keep only a decreasing stack of (price, span) and fold each popped span into today's.
PatternMonotonic Stack

Instinct Each element needs its nearest bigger or smaller neighbour (next warmer day, span, widest bar) - keep a sorted stack of waiting indices.

Memory hack Tall people block the view - a newcomer kicks out everyone shorter waiting behind, and each kicked-out person just found their answer.

Open the Monotonic Stack guide →

Approaches

Brute ForceStore History, Walk Back Day by Day

Time O(n) per callSpace O(n)

Remember every price. On each call, step backwards one day at a time while the price is at most today's, counting days. This follows the definition directly.

Java
class StockSpanner {
    private final List<Integer> prices = new ArrayList<>();

    public StockSpanner() { }

    public int next(int price) {
        prices.add(price);
        int span = 0;
        for (int j = prices.size() - 1; j >= 0 && prices.get(j) <= price; j--) {
            span++;
        }
        return span;
    }
}

Simple, but a long rising streak makes every call scan the whole history.

At a glance

LevelApproachTimeSpace
Brute ForceStore History, Walk Back Day by DayO(n) per callO(n)
BetterJump Back Using Earlier SpansO(1) amortizedO(n)
OptimalMonotonic Stack of (price, span)O(1) amortizedO(n) worst
Common pitfalls
  • Popping only on strictly smaller prices — equal prices must extend the span.
  • Pushing just the price and losing the span of the popped block.
  • Forgetting to count today itself (span starts at 1).
Interview tips
  • Clarify the online setting: you cannot look ahead, only at history.
  • Explain amortized O(1): total pops never exceed total pushes.
  • Note the stack holds the “previous greater” chain of today's price.
Pattern
Monotonic stack → streaming “how far back until a bigger value” queries.
My notes saved in this browser