15% off all plans & roadmaps Use code
See plansLeetCode 901 · Solution & editorial
Design an algorithm that collects daily price quotes for some stock and returns the span of that stock's price for the current day.
Online Stock Span is a Stack Patterns problem, in the Monotonic Stack subpattern. The pattern covers parentheses matching, monotonic stack, histogram, and expression evaluation
Master monotonic stack for next greater element, daily temperatures, and stock span problems.
The reference solution runs in O(1) amortized time and O(N) space.
Online Stock Span has been reported in interviews at Amazon.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Online Stock Span is a Stack Patterns problem, in the Monotonic Stack subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.