Ctrl K

Waiting for a Higher Price

Medium
A shop records an item's price at the end of each day: prices[i] is the price on day i. For every day, find out how many days you would have to wait until the price is strictly higher than on that day. Return a list of the same length where element i is the number of days from day i to the nearest later day with a higher price. If there is no such day, put 0. Comparing each day with all the following ones is O(n²). Try to do it in O(n).
Example 1
prices=[50, 45, 47, 60, 58] → [3, 1, 1, 0, 0]

After 50, the price first goes higher 3 days later (60). After 45 it rises the very next day (47), and after 47 too (60). Neither 60 nor 58 is ever beaten.

Example 2
prices=[70, 70, 71] → [2, 1, 0]

An equal price does not count as higher: from the first 70 it takes two days to reach 71.

Example 3
prices=[90, 80, 30] → [0, 0, 0]
Constraints
  • 1 ≤ len(prices) ≤ 10⁵
  • 1 ≤ prices[i] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPreorder of a Search Tree MediumLow, Peak, Middle MediumNext Larger Around the Circle MediumFix the Middle of the Line MediumPeak-Split Tree Medium
loading Python…
Input
prices=[50, 45, 47, 60, 58]
Expected
[3, 1, 1, 0, 0]

Run checks the first 3 tests in your browser. Submit checks all 104 tests on the server, hidden ones included.