Skip to lesson

Sliding window maximum

Unlike a running sum, you cannot undo a maximum by subtracting the outgoing element: when the largest element leaves a window of size k, who is the new runner-up? A monotonic decreasing queue built with ArrayDeque<Integer> answers that question in O(1) amortized time per slide.

ArrayDeque as a monotonic queue

In Sliding Window Maximum, given int[] nums and window size k, we want an array of length n - k + 1 containing the maximum of each k-element window.

  1. Evict expired front: if !dq.isEmpty() && dq.peekFirst() <= right - k, call dq.pollFirst().
  2. Maintain monotonic order at back: while !dq.isEmpty() && nums[dq.peekLast()] <= nums[right], call dq.pollLast().
  3. Push current index: dq.offerLast(right).
  4. Record window max: if right >= k - 1, result[right - k + 1] = nums[dq.peekFirst()].

Monotonic Deque on nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3

Step 1 of 7

Array: 1, 3, -1, -3, 5, 3, 6, 7. right at index 1.
right
1
val
3
k
3
deque (idx:val)
  1. 1:3
result(empty)
After pushing 0:1 at right = 0, right = 1 brings 3 >= 1: pop 0:1 from the back and push 1:3.

Example 1 · Brute force: scan every window for its maximum (O(n · k) time, O(1) extra space)

SlidingMaxBrute.javaJava
import java.util.Arrays;
public class SlidingMaxBrute {    public static int[] maxSlidingWindow(int[] nums, int k) {        int[] result = new int[nums.length - k + 1];        for (int start = 0; start + k <= nums.length; start++) {            int max = nums[start];            for (int i = start + 1; i < start + k; i++) {                max = Math.max(max, nums[i]);            }            result[start] = max;        }        return result;    }
    public static void main(String[] args) {        int[] nums = {1, 3, -1, -3, 5, 3, 6, 7};        System.out.println(Arrays.toString(maxSlidingWindow(nums, 3)));    }}
Output
[3, 3, 5, 5, 6, 7]

What this code does

  • Each window is scanned in full to find its largest value: n windows times k values.
  • A running sum can be updated by adding and subtracting, but a maximum cannot be undone when the old maximum leaves. A deque keeps only the values that can still become the maximum.

Example 2 · Optimal: monotonic ArrayDeque of indexes (O(n) time, O(k) space)

SlidingWindowMaxDemo.javaJava
import java.util.ArrayDeque;import java.util.Arrays;import java.util.Deque;
public class SlidingWindowMaxDemo {    public static int[] maxSlidingWindow(int[] nums, int k) {        int n = nums.length;        int[] result = new int[n - k + 1];        Deque<Integer> dq = new ArrayDeque<>();
        for (int right = 0; right < n; right++) {            if (!dq.isEmpty() && dq.peekFirst() <= right - k) {                dq.pollFirst();            }            while (!dq.isEmpty() && nums[dq.peekLast()] <= nums[right]) {                dq.pollLast();            }            dq.offerLast(right);            if (right >= k - 1) {                result[right - k + 1] = nums[dq.peekFirst()];            }        }        return result;    }
    public static void main(String[] args) {        int[] nums = {1, 3, -1, -3, 5, 3, 6, 7};        int[] maxes = maxSlidingWindow(nums, 3);        System.out.println(Arrays.toString(maxes));    }}
Output
[3, 3, 5, 5, 6, 7]

What this code does

  • At right = 1 (val 3), index 0 (val 1) is popped from the back because 1 <= 3.
  • At right = 2 (val -1), -1 < 3 so dq holds indices [1, 2] (values [3, -1]), and the front index 1 gives max 3.
  • Why it is faster: every index is added to the deque once and removed once, and the front always holds the current maximum, so each window needs O(1) work on average.

Example 3 · Step-by-step hand trace of the monotonic deque state

MonotonicDequeTraceDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;
public class MonotonicDequeTraceDemo {    public static void main(String[] args) {        int[] nums = {4, 2, 5, 1, 3};        int k = 3;        Deque<Integer> dq = new ArrayDeque<>();
        for (int r = 0; r < nums.length; r++) {            if (!dq.isEmpty() && dq.peekFirst() <= r - k) {                dq.pollFirst();            }            while (!dq.isEmpty() && nums[dq.peekLast()] <= nums[r]) {                dq.pollLast();            }            dq.offerLast(r);            StringBuilder state = new StringBuilder("[");            for (int idx : dq) {                if (state.length() > 1) state.append(", ");                state.append( idx + ":" + nums[idx]);            }            state.append("]");            String maxStr = (r >= k - 1) ? String.valueOf(nums[dq.peekFirst()]) : "-";            System.out.println("r=" + r + " (val=" + nums[r] + ") dq=" + state + " max=" + maxStr);        }    }}
Output
r=0 (val=4) dq=[0:4] max=-
r=1 (val=2) dq=[0:4, 1:2] max=-
r=2 (val=5) dq=[2:5] max=5
r=3 (val=1) dq=[2:5, 3:1] max=5
r=4 (val=3) dq=[2:5, 4:3] max=5

What this code does

  • When r=2 (val=5) arrives, both 1:2 and 0:4 are smaller than 5 and get evicted from the back, leaving only [2:5].
  • When r=4 (val=3) arrives, 3:1 is evicted because 1 <= 3, while 2:5 stays at the front.

Scanning each window takes O(n · k) time, and a max-heap (PriorityQueue) takes O(n log k) time.

Why can we do better? Suppose the window currently contains an older element nums[i] = 3 and a newer element nums[j] = 7 arrives (i < j). Because nums[j] is both larger (7 >= 3) and newer (it will stay in future windows longer than i), nums[i] can never be the maximum of the current window or any future window! We can permanently discard i. By evicting from the back (pollLast()) every index whose value is ≤ nums[right] before pushing right at the back (offerLast(right)), the ArrayDeque stays sorted in decreasing order of values from front to back. The current window's maximum is always sitting at the front (peekFirst()).

Find the bug

Find the deque bug

Tap the line that is wrong.

The deque should hold indexes, not values. Which line is wrong?

Round 1 of 3

Storing indexes, not values, and why it is O(n)

Why do we store indices (Deque<Integer>) in the ArrayDeque rather than the element values themselves?

  1. Expiration check: We need to know whether the front element has fallen out of the window [right - k + 1 .. right]. With an index idx = dq.peekFirst(), checking idx <= right - k (or idx < right - k + 1) is unambiguous, even when duplicate values exist.
  2. Value lookup: Given any index idx, we can still get its value in O(1) via nums[idx].

Why is the algorithm O(n) time despite the inner while loop? Because each of the n indices 0 .. n - 1 is pushed into dq exactly once (offerLast) and popped from dq at most once (either via pollLast when dominated by a newer larger element, or via pollFirst when expiring from the left). Across the entire loop, there are at most 2n deque operations, each O(1), giving O(n) time and O(k) auxiliary space.

In the back-eviction loop, use <= (nums[dq.peekLast()] <= nums[right]): if an equal value arrives later, the newer index will outlive the older duplicate, so keeping only the newer index bounds the deque size to at most k.

Real world: rolling metrics on dashboards

Production monitoring dashboards (Grafana, Datadog, Prometheus) and algorithmic trading engines display rolling peak latency, rolling peak CPU utilization, and 52-week/20-day price highs (Donchian channels) over live streams.

Example 4 · Dashboard jitter check: longest subarray with max - min <= limit

BoundedSpreadWindowDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;
public class BoundedSpreadWindowDemo {    public static int longestSubarrayWithinLimit(int[] nums, int limit) {        Deque<Integer> maxDq = new ArrayDeque<>();        Deque<Integer> minDq = new ArrayDeque<>();        int left = 0, best = 0;
        for (int right = 0; right < nums.length; right++) {            while (!maxDq.isEmpty() && nums[maxDq.peekLast()] <= nums[right]) {                maxDq.pollLast();            }            while (!minDq.isEmpty() && nums[minDq.peekLast()] >= nums[right]) {                minDq.pollLast();            }            maxDq.offerLast(right);            minDq.offerLast(right);
            while (nums[maxDq.peekFirst()] - nums[minDq.peekFirst()] > limit) {                if (maxDq.peekFirst() == left) maxDq.pollFirst();                if (minDq.peekFirst() == left) minDq.pollFirst();                left++;            }            best = Math.max(best, right - left + 1);        }        return best;    }
    public static void main(String[] args) {        int[] latencies = {8, 2, 4, 7};        System.out.println("Longest stable window (limit=4): " + longestSubarrayWithinLimit(latencies, 4));        int[] readings = {10, 1, 2, 4, 7, 2};        System.out.println("Longest stable window (limit=5): " + longestSubarrayWithinLimit(readings, 5));    }}
Output
Longest stable window (limit=4): 2
Longest stable window (limit=5): 4

What this code does

  • Pairing a decreasing maxDq and an increasing minDq gives both the maximum and minimum of [left .. right] in O(1) time.
  • Whenever max - min > limit, we advance left and pop left from the front of whichever deque holds it.
  • Max deque: evict back while nums[dq.peekLast()] <= nums[right] (decreasing order).
  • Min deque: evict back while nums[dq.peekLast()] >= nums[right] (increasing order).
  • Window spread at any moment: nums[maxDq.peekFirst()] - nums[minDq.peekFirst()].

Moreover, maintaining two monotonic deques simultaneously—one decreasing (maxDeque) for the window maximum and one increasing (minDeque) for the window minimum—lets a variable-size window track the spread (max - min) of any window in O(1) time! That solves Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit, which models detecting periods of low network jitter or stable asset prices.

Next step

Check your understanding

10 quick questions