Waiting for a Bigger Wave

Mediummonotonic stackAlso known as Daily Temperatures

A surf school gets an hourly forecast of wave heights, in centimetres, for the day ahead. Students who arrive at a given hour always ask the same thing: if I paddle out now, how long until a wave bigger than this one comes in?

The school wants the answer for every hour of the forecast, printed on the board each morning.

Your task

Write hoursUntilBigger(heights). heights[i] is the forecast wave height in hour i. Return a list wait of the same length, where wait[i] is the number of hours from hour i until the first later hour with a strictly taller wave. If no later hour has a taller wave, wait[i] is 0.

An empty forecast gives an empty list.

hoursUntilBigger(heights: int[]) → int[]

Examples

Example 1
Input
heights = [5, 3, 4, 8, 6, 7]
Output
[3, 1, 1, 0, 1, 0]
Why

Hour 0 (5 cm) waits until hour 3 (8 cm): 3 hours. Hour 1 (3 cm) only waits 1 hour for the 4 cm wave. Hour 2 (4 cm) waits 1 hour for 8. Nothing after hour 3 beats 8, so it gets 0. Hour 4 (6 cm) waits 1 hour for 7. The last hour has nothing after it: 0.

Example 2
Input
heights = [4, 4, 2, 4]
Output
[0, 0, 1, 0]
Why

A 4 cm wave is not bigger than another 4 cm wave. Only hour 2 (2 cm) sees a taller wave, 1 hour later.

Constraints

  • 0 ≤ heights.length ≤ 100,000
  • 1 ≤ heights[i] ≤ 1,000
Start with brute force

For each hour, scan forward until you find a taller wave. That is two nested loops.

When the forecast is mostly falling, each scan runs to the end, so the total is about n² / 2 steps. With 100,000 hours that is around 5 billion steps. The waste: the same small waves are scanned again and again by every hour that comes before them.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code