Prices arrive one per day. next(price) returns the span: the number of consecutive days, ending today and going backward, on which the price was less than or equal to today's.
Before you code
A single call may look back over many days. Which earlier days can never matter again, and how often can each day be discarded?
Hints
- Keep a stack of (price, span) pairs with strictly decreasing prices.
- For a new price, pop every pair whose price is at most the new one, adding its span to today's span, which starts at 1.
- Push (price, span) and return the span. Argue the cost: each day is pushed once and popped at most once, so n calls do O(n) work in total.
Production & complexity notes
When solving Online stock span on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Amortized analysis to reinforce the underlying pattern.
What it practices
Aggregate analysis of a monotonic stack, from Amortized analysis.