oneby7

Stacks and Queues Monotonic stack

213. Online Stock Span

Medium

The price of a stock arrives once a day, and after each price you must report that day's span. The span of a day is the number of consecutive days, ending with that day and counting back, on which the price was at most that day's price. The day itself always counts, so a span is at least 1.

Write a class StockSpanner with a constructor and one method:

  • StockSpanner() starts with no prices.
  • next(price) takes the price of the next day and returns that day's span.

Your class is tested on a new StockSpanner, which then gets one call next(prices[i]) for each price in prices, in order. The answer is the list of what each call returns.

In C# and Go the method is Next. Go creates the object with Constructor(), and Rust with StockSpanner::new().

Example 1

Input: prices = [31, 24, 27, 24, 28, 40, 35]

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

Explanation: On day 4 the price is 28. Going back, 24, 27 and 24 are all at most 28, and then 31 is higher, so the span is 4. The 40 on day 5 is the highest so far, so its span covers all 6 days. The 35 after it gets 1.

Example 2

Input: prices = [6, 6, 2, 6]

Output: [1,2,1,4]

Explanation: An earlier price equal to today's counts. So the second 6 has span 2, and the last 6 counts back over 2, 6 and 6, for a span of 4.

Example 3

Input: prices = [8, 5, 3, 1]

Output: [1,1,1,1]

Explanation: Each price is lower than the one before it, so every day counts only itself.

Check your understanding

Work out the answer for this input before you write any code.

prices = [5, 8, 3, 3, 6]

Constraints

  • 1 ≤ prices.length ≤ 105, so next is called at most 105 times.
  • 1 ≤ prices[i] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.