MediumStackDesignMonotonic StackData Stream

Online Stock Span

LeetCode
1 approach, code in all languages

Design an algorithm that computes the span of a stock's daily price as new prices stream in one at a time.

The span of the current day is the number of consecutive days ending with today (including today) for which the price was less than or equal to today's price.

Implement the `StockSpanner` class:

- `StockSpanner()` initializes the object. - `next(price)` records today's `price` and returns the span for that day.

Example 1

Input: StockSpanner(); next(100); next(80); next(60); next(70); next(60); next(75); next(85)

Output: [1, 1, 1, 2, 1, 4, 6]

70 covers itself and the prior 60 (span 2). 75 covers 60, 70, 60 and itself (span 4). 85 covers all of 80, 60, 70, 60, 75 and itself (span 6).

Example 2

Input: StockSpanner(); next(31); next(41); next(48); next(59); next(26)

Output: [1, 2, 3, 4, 1]

Each rising price extends the run: 41 spans 2, 48 spans 3, 59 spans 4. The drop to 26 resets the span to 1.

Constraints

  • 1 <= price <= 10^5
  • At most 10^4 calls will be made to next.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now