Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Stack

How many days in a row the price was no higher

Medium · Target 15 minutes · Stack· Type asked at

You're given the daily prices of a stock in prices, and the span on day i is how many days in a row (ending on day i and counting it) the price was at most prices[i]. You'd return the span for every day.

Examples

InputOutputWhy
prices = [100, 80, 60, 70, 60, 75, 85][1, 1, 1, 2, 1, 4, 6]On the sixth day the 75 reaches back over 60 and 70 and 60 until it gets to the 80 (which is higher) so you'd say its span is 4.
prices = [1, 2, 3, 4, 5][1, 2, 3, 4, 5]Every day's the highest you've seen so far and so each span goes all the way back to the start.
prices = [3, 3, 3, 3][1, 2, 3, 4]I'd point out that equal prices count here since the rule says at most.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ prices[i] ≤ 10⁵

Hints

Hint 1

If you walk back from every day it's O(n²) when the prices go up steadily, so I'd ask which of the earlier days could ever stop a span later on.

Hint 2

It's only a day that's higher than everything that's come after it so far, because once a higher or equal day turns up the earlier one's hidden behind it for good.

Hint 3

So you'd keep a stack of the days that are still visible (with prices going down from the bottom to the top) and for each new day you pop every day that's priced at most today's. Whatever's left on top (or the start, if nothing is) is where the span stops.

Where people lose marks

  • Popping only the prices that are strictly below today's, which leaves an equal earlier day on the stack and stops the span a day too early.
  • Putting prices on the stack where you'd want the indices, when it's the index of the higher day that tells you how far back the span goes.
  • Worrying that the while loop inside the for loop makes it quadratic. I wouldn't, because each index can only leave the stack once and so all the pops together come to n at most.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.