Freezer Warmest Stretch

HardqueueAlso known as Sliding Window Maximum

A restaurant's walk-in freezer logs its temperature once a minute, in °C. A food-safety rule cares about the warmest reading in every stretch of k consecutive minutes, since one warm spike matters even if the average looks fine. The inspector wants that peak for every k-minute stretch, over logs that cover whole weeks, so the report must be fast.

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

[-18, -16, -19] peaks at -16, and so does [-16, -19, -20]. Then -16 leaves: [-19, -20, -17] and [-20, -17, -21] peak at -17.

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

With k = 1 each window is 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

Scan each of the n - k + 1 windows for its maximum: O(n·k). With 100,000 readings and k = 50,000, that is 50,001 windows of 50,000 readings, about 2.5 billion comparisons, though neighbouring windows share all but one reading.

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