#901

Online Stock Span

Medium Monotonic stack with spans

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Prices arrive one per day. For each new price, return its span: the number of consecutive days up to today with price less than or equal to today's.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: how many consecutive days up to today had a price ≤ today's?

Why this works: smaller earlier prices can be merged into today's span forever; keep (price, span) on a stack.

Example: 100, 80, 60, 70, 60, 75, 85

spans 1, 1, 1, 2, 1, 4, 6

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Using < instead of <= — equal prices should be included in the span.

Solve on LeetCode ↗
Complexity
  • Time: Amortised O(1) per call.
  • Space: O(n).
Topic: Stack & Queue
🎬 Episodes 46–52: video coming soon