Freezer Warmest Stretch

HardqueueAlso known as Sliding Window Maximum

A restaurant's walk-in freezer logs its temperature once a minute, in degrees Celsius. A food-safety rule looks at every stretch of k consecutive minutes and cares about the warmest reading in that stretch: one warm spike can matter even if the average looks fine.

The inspector wants a report with the warmest reading for every possible k-minute stretch: minutes 0 to k - 1, then 1 to k, and so on to the end of the log. Logs cover whole weeks, so the report must be quick to compute.

Your task

Write warmestStretches(temps, k). Return a list with one entry for each window of k consecutive readings, in order from the start: the largest value in that window. A log of n readings has n - k + 1 windows.

Aim for O(n) time in total, no matter how large k is.

warmestStretches(temps: int[], k: int) → int[]

Examples

Example 1
Input
temps = [-18, -16, -19, -20, -17, -21]
k = 3
Output
[-16, -16, -17, -17]
Why

Windows of 3: [-18, -16, -19] peaks at -16. [-16, -19, -20] still has -16. [-19, -20, -17] peaks at -17, because -16 has left. [-20, -17, -21] peaks at -17.

Example 2
Input
temps = [-6, -9, -12]
k = 1
Output
[-6, -9, -12]
Why

With k = 1 every window holds one reading, so the report is the log itself.

Constraints

  • 1 ≤ temps.length ≤ 100,000
  • 1 ≤ k ≤ temps.length
  • -40 ≤ temps[i] ≤ 40
Start with brute force

For each of the n - k + 1 windows, scan its k readings and take the maximum.

That is O(n·k). With 100,000 readings and k = 50,000 there are 50,001 windows of 50,000 readings each: about 2.5 billion comparisons. Neighbouring windows share all but one reading, yet every scan starts from nothing.

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