Skip to content

visual walkthrough

Online Stock Span

MediumMonotonic StackReported at: AmazonBloombergAdobe

Previous-greater spans in a streaming (online) setting.

Solve on LeetCode

The idea

The span ends at the first earlier day with a higher price. A stack of (price, span) pairs remembers, for each surviving price, how many days it already covers.

A new price pops every smaller-or-equal price and adds their spans, so no day is ever re-examined.

Complexity

approachtimespace
Look back each dayO(n²)O(1)
Monotonic stackO(n)O(n)

More walkthroughs