Waiting for a Bigger Wave

Mediummonotonic stackAlso known as Daily Temperatures

A surf school gets an hourly forecast of wave heights, in centimetres. Students who arrive at any hour ask how long they would wait for a bigger wave if they paddled out right then.

The school posts the answer for every hour 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 3 hours for hour 3 (8 cm). Hour 1 (3 cm) waits only 1 hour for the 4 cm wave, and hour 2 (4 cm) waits 1 hour for the 8 cm wave. No later wave beats the 8 cm wave at hour 3, so its answer is 0. Hour 4 (6 cm) waits 1 hour for the 7 cm wave, and the last hour has no later hours, so its answer is 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 a taller wave is found, which takes two nested loops.

On a mostly falling forecast each scan runs to the end: which is about n² / 2 steps, or around 5 billion for 100,000 hours. Every earlier hour rescans the same small waves.

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