Sliding Window

Maintain a contiguous window that grows and shrinks to find the best subarray or substring in a single O(n) pass.

Intermediate 2 min readLesson 4 of 25 Interview Q&A

A sliding window is a contiguous range [L, R] over an array or string. Instead of recomputing every subarray from scratch (O(n²) or worse), you slide the window: add the element entering on the right, remove the one leaving on the left, and update the answer incrementally. Each element enters and leaves at most once → O(n).

InteractiveSliding window — longest substring without repeats
a
0
L,R
b
1
c
2
a
3
b
4
c
5
b
6
b
7
x
8
y
9
z
10
windowduplicate
Window "a" (len 1). Best so far: "a"
1/17
When to use this pattern
  • The problem asks about a contiguous subarray or substring.
  • You want the longest / shortest / count / maximum sum of windows satisfying a condition.
  • The condition can be updated incrementally as elements enter and leave (counts, sums, distinct characters).
  • Typical wording: "longest substring with at most k distinct…", "minimum window containing…", "maximum sum of size k".

Fixed-size window

Maximum sum of any subarray of size k
int maxSumK(int[] a, int k) {
    int sum = 0, best;
    for (int i = 0; i < k; i++) sum += a[i];
    best = sum;
    for (int r = k; r < a.length; r++) {
        sum += a[r] - a[r - k];        // add incoming, remove outgoing
        best = Math.max(best, sum);
    }
    return best;
}

Variable-size window: the universal template

L = 0
for R in 0..n-1:
    add a[R] to the window state
    while the window is INVALID:        # (for "longest" problems)
        remove a[L] from the state; L++
    update answer with window [L, R]    # e.g. best = max(best, R - L + 1)

For "shortest" problems flip it: while the window is VALID, record the answer and shrink.

Longest substring without repeating characters
int lengthOfLongestSubstring(String s) {
    Map<Character, Integer> last = new HashMap<>();   // char → last index
    int best = 0;
    for (int l = 0, r = 0; r < s.length(); r++) {
        char c = s.charAt(r);
        if (last.containsKey(c) && last.get(c) >= l) l = last.get(c) + 1;  // jump L past the duplicate
        last.put(c, r);
        best = Math.max(best, r - l + 1);
    }
    return best;
}
Minimum window substring (shortest valid window)
String minWindow(String s, String t) {
    int[] need = new int[128];
    for (char c : t.toCharArray()) need[c]++;
    int missing = t.length(), bestL = 0, bestLen = Integer.MAX_VALUE;
    for (int l = 0, r = 0; r < s.length(); r++) {
        if (need[s.charAt(r)]-- > 0) missing--;          // a needed char entered
        while (missing == 0) {                           // window VALID → try to shrink
            if (r - l + 1 < bestLen) { bestLen = r - l + 1; bestL = l; }
            if (++need[s.charAt(l++)] > 0) missing++;    // a needed char left
        }
    }
    return bestLen == Integer.MAX_VALUE ? "" : s.substring(bestL, bestL + bestLen);
}

Window maximum with a monotonic deque

"Maximum of every window of size k" needs more than a sum. Keep a deque of indices whose values are decreasing: the front is always the window's maximum. Pop smaller values from the back before pushing; pop the front when it leaves the window. O(n).

Sliding window maximum
int[] maxSlidingWindow(int[] a, int k) {
    int[] res = new int[a.length - k + 1];
    Deque<Integer> dq = new ArrayDeque<>();          // indices, values decreasing
    for (int i = 0; i < a.length; i++) {
        while (!dq.isEmpty() && a[dq.peekLast()] <= a[i]) dq.pollLast();
        dq.offerLast(i);
        if (dq.peekFirst() <= i - k) dq.pollFirst(); // left the window
        if (i >= k - 1) res[i - k + 1] = a[dq.peekFirst()];
    }
    return res;
}
Practice problems
  • Maximum Average Subarray Ifixed windoweasy
  • Best Time to Buy and Sell Stocktrack min so fareasy
  • Longest Substring Without Repeating Charactersmedium
  • Longest Repeating Character Replacementlen − maxFreq ≤ kmedium
  • Permutation in Stringfixed window of countsmedium
  • Find All Anagrams in a Stringmedium
  • Minimum Size Subarray Sumshrink while validmedium
  • Fruit Into Basketsat most 2 distinctmedium
  • Max Consecutive Ones IIIat most k zerosmedium
  • Subarrays with K Different IntegersatMost(k) − atMost(k−1)hard
  • Minimum Window Substringhard
  • Sliding Window Maximummonotonic dequehard
Key takeaways
  • Use for contiguous subarray/substring problems with incrementally maintainable state.
  • Fixed window: add one, remove one. Variable window: expand R, shrink L while invalid (or while valid, for "shortest").
  • Each index enters and leaves once → O(n).
  • "Exactly k" = atMost(k) − atMost(k − 1).
  • Window min/max needs a monotonic deque.
Interview questions
QWhy can't sliding window solve 'subarray sum equals k' with negative numbers?medium

With negatives, extending the window can decrease the sum and shrinking can increase it, so there's no monotonic rule for when to move L. Use prefix sums with a hash map of seen prefix sums instead: O(n).

QLongest repeating character replacement: why don't you decrease maxFreq when shrinking?hard

The answer only grows when a window with a higher maxFreq appears. A stale (too high) maxFreq can only keep the window the same size, never produce a wrong larger answer, so it's safe and keeps the algorithm O(n).