Online Stock Span
Problem Statement
Build a class StockSpanner that receives a stock's price one day at a time.
Each call next(price) gives you today's price and must return today's span: the number of days in a row, ending today and going backwards, on which the price was less than or equal to today's price. Today itself counts, so the span is at least 1.
You do not get the prices in advance β you must answer each call before you see the next price.
A sequence of calls: StockSpanner() once, then next(price) many times.
For each next(price) call, an integer: today's span.
For 75: going back, 60, 70, 60 are all β€ 75, and 80 is higher, so the span is 4. For 85: everything back to 100 is β€ 85, so the span is 6.
- β’ 1 β€ price β€ 10^5
- β’ At most 10^4 calls to `next`
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Store all prices; each call counts backwards while prices are β€ today
Each stack entry stands for a whole run of days; popped spans fold into the new one
Keep every price in a vector. On each next(price), append it, then walk back from the second-last price while prices are β€ price, counting as you go.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Monotonic Stack translate into production architectures and low-level memory mechanics.