Tech Interview RoomStudy guides

Sliding Window

Sliding window maximum. Compare brute force, a heap / TreeMap and the monotonic deque.

Advanced · 2 min read · Lesson 5 of 5 in Sliding Window

Problem

Return the maximum of every window of size k. nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3 → [3, 3, 5, 5, 6, 7].

Pattern

Monotonic deque: keep indices whose values are in decreasing order; anything smaller than a newer element can never be a future maximum, so it is dropped. The front is always the current maximum.

Approach 1: Scan every window (feasible, O(n·k))

java
class WindowMaxBrute {
    static int[] max(int[] a, int k) {
        int[] out = new int[a.length - k + 1];
        for (int i = 0; i < out.length; i++) {
            int m = Integer.MIN_VALUE;
            for (int j = i; j < i + k; j++) m = Math.max(m, a[j]);
            out[i] = m;
        }
        return out;
    }
}

Approach 2: TreeMap as a multiset (O(n log k))

A max-heap also works with lazy deletion; a TreeMap<value, count> supports removing the leaving element directly.

java
import java.util.TreeMap;

class WindowMaxTreeMap {
    static int[] max(int[] a, int k) {
        TreeMap<Integer, Integer> window = new TreeMap<>();
        int[] out = new int[a.length - k + 1];
        for (int i = 0; i < a.length; i++) {
            window.merge(a[i], 1, Integer::sum);
            if (i >= k) {
                int leaving = a[i - k];
                if (window.merge(leaving, -1, Integer::sum) == 0) window.remove(leaving);
            }
            if (i >= k - 1) out[i - k + 1] = window.lastKey();
        }
        return out;
    }
}

Approach 3: Monotonic deque (O(n)) — optimal

java
import java.util.ArrayDeque;
import java.util.Deque;

class WindowMaxDeque {
    static int[] max(int[] a, int k) {
        int[] out = new int[a.length - k + 1];
        Deque<Integer> dq = new ArrayDeque<>();                  // indices, values decreasing
        for (int i = 0; i < a.length; i++) {
            if (!dq.isEmpty() && dq.peekFirst() <= i - k) dq.pollFirst();     // left the window
            while (!dq.isEmpty() && a[dq.peekLast()] <= a[i]) dq.pollLast();  // can never be max again
            dq.offerLast(i);
            if (i >= k - 1) out[i - k + 1] = a[dq.peekFirst()];
        }
        return out;
    }
}

class WindowMaxDemo {
    public static void main(String[] args) {
        int[] a = {1, 3, -1, -3, 5, 3, 6, 7};
        System.out.println(java.util.Arrays.toString(WindowMaxBrute.max(a, 3)) + " "
            + java.util.Arrays.toString(WindowMaxTreeMap.max(a, 3)) + " " + java.util.Arrays.toString(WindowMaxDeque.max(a, 3)));
        // [3, 3, 5, 5, 6, 7] x3
    }
}

Feasible → optimal

O(n·k) → O(n log k) with an ordered structure → O(n) with a monotonic deque, because each index is pushed and popped at most once.

Follow-up questions interviewers ask

Try answering each one before you open it.

Related (same pattern): shortest subarray with sum at least K when numbers can be negative.

Prefix sums plus a monotonic increasing deque of prefix indices: for each j, pop from the front while prefix[j] - prefix[front] >= K (recording the length), and pop from the back while prefix[back] >= prefix[j]. O(n). This is where the plain sliding window fails and the deque saves you.

Related (same pattern): longest subarray where max − min ≤ limit.

Keep two monotonic deques (one decreasing for the max, one increasing for the min) inside a variable window; shrink from the left while max - min > limit. O(n).