Sliding Window Maximum solution explained

Sliding Window Maximum is solved with a monotonic deque: keep the indexes of possible maximums in a double-ended queue whose values only decrease from front to back, drop the front when it leaves the window, and drop from the back any value that the new element beats. The front is always the current maximum, every index enters and leaves once, and the whole pass is O(n) instead of the O(n · k) of rescanning each window.

By Published 9 min read

What you are asked to do

You receive a list of integers and a window size k between 1 and the list length. Place a frame over the first k entries, write down the largest value inside it, move the frame one position to the right, and repeat until the frame touches the last entry. Return the list of values you wrote down. An array of length n produces n - k + 1 answers.

Arrays made up for this walkthrough, outputs produced by the tested code
ArraykMaximum of each window
[2, 7, 3, 1, 6, 4, 5]3[7, 7, 6, 6, 6]
[9, 8, 7, 6]2[9, 8, 7]
[1, 2, 3, 4]2[2, 3, 4]
[10, 4, 4, 9, 1]2[10, 4, 9, 9]
[4, -2, 8]3[8]
[-3, -1, -2]1[-3, -1, -2]
Arrays made up for this walkthrough, outputs produced by the tested code. Scroll sideways on a small screen.

Clarify before coding: can k be larger than the array (usually no, but if yes, decide whether to return nothing or one overall maximum), can values be negative or repeated (yes in most versions), and do they want the maximums or their positions. Positions are a one-line change in the deque version, since it already stores indexes.

Where it sits in a coding loop

Interviewers tend to use this as the harder follow-on to an easy fixed-size window question, such as the largest sum of k consecutive values. A sum can be updated in constant time when one value enters and one leaves. A maximum cannot, because when the current maximum leaves you have no idea what the next largest is. The question is really asking whether you know a structure that answers that, and whether you can argue its running time is linear even though it contains a nested loop.

First answer: take the max of every window

Slice each window and call max on it. There are n - k + 1 windows and each scan looks at k values, so the cost is O(n · k), which degrades to quadratic when k is about half of n. It is correct and makes a good reference for testing the faster code.

def window_peaks_brute(nums, k):
    return [max(nums[i:i + k]) for i in range(len(nums) - k + 1)]
Rescan each window, O(n · k).

Middle answer: a heap with lazy deletion

A max-heap gives the largest value in O(1) and accepts new values in O(log n). The trouble is removing the value that slides out, since heaps do not support deleting an arbitrary item cheaply. The workaround is to store each value with its index and, before reading the top, pop any entries whose index is already outside the window. Stale entries can sit lower in the heap for a while, which is harmless because only the top is ever read. Each index is pushed once and popped at most once, so the total is O(n log n) time and O(n) space.

import heapq


def window_peaks_heap(nums, k):
    heap = []  # (negated value, index) so the largest value is on top
    peaks = []
    for i, value in enumerate(nums):
        heapq.heappush(heap, (-value, i))
        if i >= k - 1:
            while heap[0][1] <= i - k:
                heapq.heappop(heap)  # stale: its index left the window
            peaks.append(-heap[0][0])
    return peaks
Python's heapq is a min-heap, so values are negated.

Linear answer: the monotonic deque

The key observation is about dominated values. If a value sits to the left of a larger or equal value, it will leave the window first and is never larger while both are inside. So it can never again be the answer, and you can forget it immediately. After forgetting every dominated value, what remains, read from left to right, is strictly decreasing. The first remaining index holds the maximum.

  1. Expire the frontIf the index at the front of the deque is at or before i - k, it has slid out of the window. Remove it.
  2. Clear dominated values from the backWhile the value at the back is less than or equal to the new value, pop it. Those entries can never be a maximum again.
  3. Add the new indexPush the current index on the back. The deque is still decreasing in value from front to back.
  4. Record once the first window is fullFrom index k - 1 onward, the value at the front index is the maximum of the current window.
from collections import deque


def window_peaks(nums, k):
    keep = deque()  # indexes; their values strictly decrease front to back
    peaks = []
    for i, value in enumerate(nums):
        if keep and keep[0] <= i - k:
            keep.popleft()  # front index slid out of the window
        while keep and nums[keep[-1]] <= value:
            keep.pop()  # can never be a maximum again
        keep.append(i)
        if i >= k - 1:
            peaks.append(nums[keep[0]])
    return peaks
Python: collections.deque gives O(1) pops at both ends.
#include <deque>
#include <vector>

std::vector<int> windowPeaks(const std::vector<int>& nums, int k) {
    std::deque<int> keep;  // indexes, values strictly decreasing
    std::vector<int> peaks;
    for (int i = 0; i < static_cast<int>(nums.size()); ++i) {
        if (!keep.empty() && keep.front() <= i - k) {
            keep.pop_front();
        }
        while (!keep.empty() && nums[keep.back()] <= nums[i]) {
            keep.pop_back();
        }
        keep.push_back(i);
        if (i >= k - 1) {
            peaks.push_back(nums[keep.front()]);
        }
    }
    return peaks;
}
C++17: std::deque of indexes, same four steps.

Only one index can expire per step, because the window moves by one, so a single if at the front is enough. Popping equal values from the back, with <=, keeps the newest copy of a repeated maximum, which stays in the window longest. Using < also gives correct maximums, but the deque holds more entries.

Watching the deque work

[2, 7, 3, 1, 6, 4, 5] with k = 3, deque shown as index:value from front to back
iNew valueRemovedDeque afterOutput
02nothing0:2window not full
170:2 from the back1:7window not full
23nothing1:7, 2:37
31nothing1:7, 2:3, 3:17
461:7 expired; 3:1 and 2:3 from the back4:66
54nothing4:6, 5:46
655:4 from the back4:6, 6:56
[2, 7, 3, 1, 6, 4, 5] with k = 3, deque shown as index:value from front to back. Scroll sideways on a small screen.

Step 4 shows both kinds of removal at once. The 7 at index 1 is no longer inside the window that covers indexes 2 to 4, so it leaves from the front, and the new 6 beats both 1 and 3, so they leave from the back.

Why the nested loop is still linear

The inner while can pop several entries in one step, which looks quadratic. Count the work differently: every index is appended exactly once and removed at most once, from either end. Over the whole run that is at most 2n deque operations plus the constant work per step, so the time is O(n). The deque never holds more than k indexes, so the extra space is O(k), plus the output list.

n is the array length, k the window size
ApproachTimeExtra spaceNotes
Max of each sliceO(n · k)O(k) per sliceReference only
Heap with lazy removalO(n log n)O(n)Good stepping stone, easy to explain
Monotonic dequeO(n)O(k)The expected answer
Block prefix and suffix maximaO(n)O(n)No deque needed, two passes over blocks of size k
n is the array length, k the window size. Scroll sideways on a small screen.

The last row is a lesser-known alternative: split the array into blocks of size k, compute running maxima inside each block once scanning left to right and once scanning right to left, and each window's answer is the larger of the right-to-left value at its first index and the left-to-right value at its last index. Any window spans at most two blocks, which is why two lookups suffice. It is worth a sentence if the interviewer asks for another linear method.

Cases that catch bugs

  • k = 1: every value is its own window maximum, and the output equals the input.
  • k equal to the array length: exactly one answer, the overall maximum.
  • Strictly decreasing input: nothing is popped from the back, so expiry at the front does all the work.
  • Strictly increasing input: every new value clears the whole deque.
  • Repeated maximums, like [10, 4, 4, 9, 1] with k = 2, where equal values sit next to each other.
  • All negative values, which breaks code that initializes a running maximum to zero.

Typical errors

  • Storing values instead of indexes, which leaves no way to tell when the front has left the window.
  • Expiring with < i - k instead of <= i - k, an off-by-one that keeps one stale index for a step.
  • Reading the front before the first window is full and emitting k - 1 extra values.
  • Using a Python list with pop(0), which is O(k) per call and quietly ruins the bound.
  • Calling the deque solution O(n · k) because of the inner loop, or failing to explain why it is not.

How to explain it out loud

Fictional example

From heap to deque without losing the interviewer
Candidate
Rescanning each window is n times k. A heap gets me to n log n if I store indexes and lazily pop anything that has left the window.
Interviewer
Can you get rid of the log?
Candidate
Yes. If a value has a bigger value to its right inside the window, it can never be the maximum again, so I can discard it. If I discard all of those, the indexes I keep have decreasing values, and the front is the answer.
Candidate
Each index goes in once and comes out once, so even with the inner loop it is linear, and the deque holds at most k indexes.

Follow-ups

  • Window minimum instead. Flip the comparison so values increase from front to back.
  • Both the max and the min, for example to find windows whose spread stays under a limit. Run two deques side by side; with a variable-size window this becomes a classic two-pointer problem.
  • Data arrives as a stream. The deque version already works online: it needs only the last k indexes, not the whole array.
  • Return positions instead of values. Emit the front index rather than the value it points to.

Minimum Window Substring moves to a window whose size changes, with a count table deciding when it may shrink. Trapping Rain Water has a stack-based answer that relies on the same monotonic idea, without the expiry at the front. For the simpler variable window over characters, see Longest Substring Without Repeating Characters. Every problem is grouped by pattern on the coding problems hub.

Practicing the deque with Natively

A trace table like the one above is the best test of whether you understand the deque, so try producing one aloud before you write code. Natively, a desktop app for Mac and Windows, keeps a transcript of that mock session, which makes it easy to check later whether you explained the expiry rule and the linear-time argument or skipped them. When you are stuck in practice, it can also read the problem from a screenshot and suggest a direction. Details are on the AI assistant for coding interviews page.

Questions people ask

What is the best solution to Sliding Window Maximum?

A monotonic deque of indexes. Drop the front index once it leaves the window, pop from the back every value the new element is at least as large as, push the new index, and read the maximum from the front. It runs in O(n) time.

Why is the deque solution O(n) if it has a nested loop?

Each index is pushed once and removed at most once over the whole run, so the total number of deque operations is at most 2n no matter how the pops are spread across steps.

Can I solve Sliding Window Maximum with a heap?

Yes. Push value and index pairs into a max-heap and, before reading the top, pop entries whose index has left the window. That is O(n log n) time and a good intermediate answer.

Why store indexes in the deque rather than values?

The index tells you when an entry has slid out of the window. With values alone you could not tell an expired maximum from a newer equal one.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP