Skip to content
Decoder

Online Stock Span

Medium

Problem

Build a class StockSpanner that receives a stock's price one day at a time and reports each day's span. The span of today's price is the number of consecutive days, counting today and going backwards, on which the price was less than or equal to today's price.

- next(price) records today's price and returns today's span.

Example 1

prices in order:  100, 80, 60, 70, 60, 75, 85

Example 2

spans returned:     1,  1,  1,  2,  1,  4,  6

For 75, the run backwards is 75, 60, 70, 60 (four days), and it stops at 80, which is bigger.

Constraints

  • 1 <= price <= 10^5
  • At most 10^4 calls are made to next.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.