Community Problem

Online Stock Span

Difficulty: Medium

Design an online structure that returns the streak of consecutive previous days with price <= today, using a monotonic stack of (price, span) pairs.

Online Stock Span

Design an online structure that returns the streak of consecutive previous days with price <= today, using a monotonic stack of (price, span) pairs.

MEDIUM
Free
monotonic-stack
stack
online-algorithms
nehawood

By @nehawood

March 20, 2026

·

Updated May 20, 2026

349 views

7

Rate

Got asked this on a Bloomberg phone screen and the trap was the streaming nature: the interviewer pushes O(n) days at you and watches whether your per-call cost stays amortized O(1) instead of degrading to O(n). The monotonic stack of (price, span) pairs is the answer; the trick is what you store on the stack and what you do during the pop loop.

Online Stock Span

Design a class StockSpanner that processes the daily prices of a stock as a stream and returns the span of the most recent day's price. The span is defined as the maximum number of consecutive days (ending with today, going backwards) where the price has been less than or equal to today's price.

For example, with daily prices [100, 80, 60, 70, 60, 75, 85], the span values are [1, 1, 1, 2, 1, 4, 6].

Implement:

  • StockSpanner() constructs the spanner.
  • int next(int price) returns the span for today's price price.

The next method is called once per day in chronological order.

Examples

Example 1:

  • Input: feed [100, 80, 60, 70, 60, 75, 85] one at a time.
  • Output: [1, 1, 1, 2, 1, 4, 6]
  • Explanation: At day 3 (price 70), days 60 and 70 are <= 70 so span is 2. At day 5 (price 75), 75 >= 60, 70, 60, 75 so span is 4. At day 6 (price 85), the chain reaches all the way back except for the leading 100, so span is 6.

Example 2:

  • Input: feed [10, 4, 5, 90, 120, 80]
  • Output: [1, 1, 2, 4, 5, 1]
  • Explanation: 90 swallows 4, 5, and itself for span 4. 120 swallows everything before it for span 5.

Example 3:

  • Input: feed [31, 41, 48, 59, 79]
  • Output: [1, 2, 3, 4, 5]
  • Explanation: Strictly increasing sequence; each new price absorbs the entire history.

Example 4:

  • Input: feed [7, 6, 5, 4, 3]
  • Output: [1, 1, 1, 1, 1]
  • Explanation: Strictly decreasing sequence; every span is 1.

Constraints

  • 1 <= price <= 10^5
  • At most 10^4 calls to next.

Follow-up

What is the amortized time complexity of next? Why does a naive backward-scan give O(n^2) for n calls but the monotonic stack gives O(n) total?

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems