What is the sliding window maximum problem?

Why Interviewers Ask This

This question targets practical, hands-on experience with Data Structures & Algorithms. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.

Answer

The Sliding Window Maximum problem: given an array and window size k, find the maximum in each window of size k as the window slides from left to right. Naive: O(n×k). Optimal with monotonic deque: O(n). Key insight: maintain a deque of indices in decreasing order of their values — the front is always the maximum of the current window. Algorithm: for each element i: (1) Remove from front indices that are out of the current window (index ≤ i-k); (2) Remove from back all indices with value ≤ arr[i] (they can never be the maximum in any future window where arr[i] is present); (3) Add i to back; (4) When i ≥ k-1, record arr[deque.front()] as the window maximum. The deque is always in decreasing order of values — this is a monotonic decreasing deque. Time: O(n) — each element is added and removed at most once. Space: O(k) for the deque. Applications: (1) This exact problem (Leetcode 239); (2) Jump Game VI (maximum score in k-window DP); (3) Constrained subset sum; (4) Finding spans in stock problems. The monotonic stack/deque technique is broadly applicable to "nearest greater/smaller" element problems, stock span, and sliding window optimization of DP recurrences.

Pro Tip

This topic has Data Structures & Algorithms-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.