Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Sliding window

Maximum of every window

Hard · Target 25 minutes · Sliding window · Type asked atAmazonCitadel

Given an array nums and a window size k, return the maximum of every contiguous window of length k, from left to right.

Examples

InputOutputWhy
nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3[3, 3, 5, 5, 6, 7]Six windows; the third is [-1, -3, 5].
nums = [9, 8, 7, 6], k = 2[9, 8, 7]A falling array: each window's maximum is its first element.
nums = [4, 2, 12, 3], k = 1[4, 2, 12, 3]Windows of one element.

Constraints

  • 1 ≤ k ≤ n ≤ 10⁵
  • −10⁴ ≤ nums[i] ≤ 10⁴

Hints

Hint 1

Recomputing the maximum of each window costs O(k), so O(nk) in all. What information from the previous window could be kept?

Hint 2

Once a larger element arrives, every smaller element before it can never again be a window's maximum: it leaves the window first and is beaten for as long as it stays.

Hint 3

Keep the indices of the surviving candidates in a deque, values falling from front to back. Pop smaller values from the back before pushing; pop the front when it falls out of the window. The front is the answer.

Where people lose marks

  • Storing values instead of indices. With values alone you cannot tell whether the front has left the window, and duplicates make it worse.
  • Popping only strictly smaller values. That works, but keeps equal values and lets the deque grow; popping values that are smaller or equal is simpler and still correct.
  • Expiring the front with < i − k instead of ≤ i − k. The window ending at i starts at i − k + 1.
  • Reporting before the first window is complete: the first answer belongs to index k − 1.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.