Sliding Window Maximum

50 min · maxSlidingWindow()

A monitoring chart rarely cares about one reading in isolation. It asks a moving question: what was the highest value in the most recent block?

Given an integer array nums and a window length k, return the maximum value from every contiguous window — a block of neighboring elements — of length k, ordered from left to right.

The first window covers positions 0 through k - 1. Then it moves one position right at a time until its right edge reaches the end of the array.

  • Windows overlap; a value may contribute to several answers.
  • Preserve the left-to-right order of the windows.
  • The returned array has exactly nums.length - k + 1 values.

Constraints

  • 1 <= k <= nums.length <= 100_000
  • -100_000 <= nums[i] <= 100_000

Hints

Write the honest baseline

For each starting position, scan the next k values and keep their maximum. Now count how many repeated comparisons happen when two neighboring windows overlap.

Retire values with no future

If a new value is at least as large as an older value still in the window, the older one can never become a future maximum: it leaves first and loses every comparison.

Keep indices, not just values

Store candidate indices in decreasing order of their values. The front gives the maximum, and its index tells you exactly when that candidate has left the window.

Follow-up

How would you expose the same result one value at a time if the readings arrived as a stream and you could retain only O(k) state?

Visible cases

Examples

Example 1

ready
Input
nums = [
  1,
  3,
  -1,
  -3,
  5,
  3,
  6,
  7
]
k = 3
Expected
[
  3,
  3,
  5,
  5,
  6,
  7
]
Why
each answer is the largest value in the next three-position window

Example 2

ready
Input
nums = [
  -4,
  2,
  2,
  9
]
k = 1
Expected
[
  -4,
  2,
  2,
  9
]
Why
a one-value window has that value as its maximum

Example 3

ready
Input
nums = [
  7,
  1,
  5,
  3
]
k = 4
Expected
[
  7
]
Why
one whole-array window produces one maximum

Interview signal

Asked at

AmazonGoogleBloomberg
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite