Stock Span Simulator

For each day, the stock span is the number of consecutive days ending on that day for which the price was less than or equal to the current price. A monotonic decreasing stack computes all spans in linear time.

Naive solutionO(n²)
Stack solutionO(n)
Auxiliary spaceO(n)
Stack storesIndices

Simulation controls

500 ms

Price chart and computed spans

Monotonic stack

TOP

Use Next Step to process the first day.

Current day0 / 7
Comparisons0
Pushes / pops0 / 0
ComplexityO(n)

Results

DayPriceSpan

Monotonic-stack algorithm

for i = 0 ... n-1:
  while stack not empty
        and price[stack.top] <= price[i]:
    stack.pop()

  if stack empty:
    span[i] = i + 1
  else:
    span[i] = i - stack.top

  stack.push(i)

Why the stack solution is O(n)

Monotonic invariant

Indices in the stack refer to prices that decrease from bottom to top.

Each index is pushed once

Every day enters the stack exactly once when its span has been computed.

Each index is popped at most once

Once a smaller or equal price is removed, it never returns to the stack.

Amortized reasoning

Across all days there are at most n pushes and n pops, so total stack work is linear.