Magicsheet logo

Sliding Window Maximum

Hard
73.1%
Updated 6/1/2025

Sliding Window Maximum

What is this problem about?

The "Sliding Window Maximum" interview question is a legendary "HARD" level challenge. You are given an array of integers and a sliding window of size k that moves from the left to the right of the array. For each position of the window, you need to find the maximum element. This "Sliding Window Maximum coding problem" is difficult because the naive approach of scanning the entire window at each step takes O(N * K) time, which is unacceptable for large datasets. You must find an O(N) solution.

Why is this asked in interviews?

This problem is asked by nearly every top-tier tech company, including Google, Meta, and Amazon. It tests whether a candidate can use advanced data structures like a Monotonic Queue or a Deque (Double-Ended Queue) to maintain state efficiently. It evaluates your ability to handle sliding window constraints and optimize for amortized linear time complexity. This is a critical skill for high-performance computing and real-time data processing.

Algorithmic pattern used

The primary pattern is the "Monotonic Queue and Sliding Window interview pattern". You use a deque to store the indices of elements. The deque will maintain the property that the elements corresponding to its indices are in strictly decreasing order.

  1. When a new element arrives, remove all indices from the back of the deque whose values are less than the new element.
  2. Add the new index to the back.
  3. Remove the index from the front if it's no longer within the sliding window range.
  4. The front of the deque always contains the index of the maximum element for the current window.

Example explanation

Array: [1, 3, -1, -3, 5, 3, 6, 7], k=3

  1. Window [1, 3, -1]: Max is 3. Deque: [1] (index of 3).
  2. Window [3, -1, -3]: Max is 3. Deque: [1, 2, 3] (indices of 3, -1, -3).
  3. Window [-1, -3, 5]: 5 is greater than -1 and -3. Deque: [4] (index of 5). Max is 5.
  4. Window [-3, 5, 3]: Max is 5. Deque: [4, 5] (indices of 5, 3).
  5. Window [5, 3, 6]: 6 is greater than 5 and 3. Deque: [6] (index of 6). Max is 6. Result: [3, 3, 5, 5, 6, 7].

Common mistakes candidates make

The most common mistake is a naive O(N*K) solution, which will fail the time limits. Another error is storing values instead of indices in the deque, which makes it harder to check if the maximum element has "expired" (fallen out of the window). Many candidates also struggle to implement the "monotonic" property correctly, often forgetting to clear smaller elements from the back of the queue.

Interview preparation tip

The Monotonic Queue is a powerful pattern for any "Sliding Window Maximum interview question". It allows you to maintain the "best" candidate in O(1) amortized time. Practice implementing this with a deque until you can write it flawlessly, as it appears in many high-stakes coding rounds.

Similar Questions