Sliding Window Patterns

Loading concept...

πŸͺŸ Sliding Window Patterns: The Magic Window Technique


🎭 The Story of the Curious Window

Imagine you’re looking through a small window on a moving train. You can only see a little bit of the world at a time. As the train moves, your view shiftsβ€”old scenery slides out, new scenery slides in.

This is exactly how the Sliding Window technique works in programming!

Instead of looking at an entire array again and again (slow!), we look through a β€œwindow” and slide it alongβ€”keeping what we need, dropping what we don’t.


🧩 Why Sliding Window?

❌ Brute Force: Check EVERY possible subarray
   β†’ Slow like reading the whole book for each question

βœ… Sliding Window: Slide and adjust smartly
   β†’ Fast like moving your bookmark as you read

πŸ“ Pattern 1: Fixed Size Sliding Window

The Idea

Your window has a fixed size (like a photo frame). You slide it across the array one step at a time.

Real Life Example

You have a row of 10 ice cream shops. You want to find the 3 consecutive shops that sell the most ice cream together.

How It Works

graph TD A["Array: [2,1,5,1,3,2]"] --> B["Window size = 3"] B --> C["Window 1: [2,1,5] = 8"] C --> D["Window 2: [1,5,1] = 7"] D --> E["Window 3: [5,1,3] = 9 βœ“"] E --> F["Window 4: [1,3,2] = 6"] F --> G["Max Sum = 9"]

Java Code

int maxSum(int[] arr, int k) {
    int n = arr.length;
    if (n < k) return -1;

    // Build first window
    int windowSum = 0;
    for (int i = 0; i < k; i++) {
        windowSum += arr[i];
    }

    int maxSum = windowSum;

    // Slide: add new, remove old
    for (int i = k; i < n; i++) {
        windowSum += arr[i];      // add new
        windowSum -= arr[i - k];  // remove old
        maxSum = Math.max(maxSum, windowSum);
    }

    return maxSum;
}

Key Insight

Add one at the front, remove one from the back. Like a caterpillar moving forward!


πŸ“ Pattern 2: Variable Size Sliding Window

The Idea

Now your window can stretch and shrink like a rubber band! You expand it to grab more, shrink it when you’ve grabbed too much.

Real Life Example

Find the shortest line of people at a store whose combined money is at least $100.

How It Works

graph TD A["Goal: Find smallest window β‰₯ target"] A --> B["Expand window #40;add right#41;"] B --> C{Sum β‰₯ target?} C -->|No| B C -->|Yes| D["Shrink window #40;remove left#41;"] D --> E["Record size if smaller"] E --> C

The Two-Pointer Dance

LEFT pointer β†’ shrinks the window
RIGHT pointer β†’ expands the window

They never cross. They dance together!

🎯 Pattern 3: Minimum Size Subarray Sum

The Problem

Given an array and a target, find the smallest subarray whose sum is β‰₯ target.

Example

Array:  [2, 3, 1, 2, 4, 3]
Target: 7

Answer: 2 (subarray [4,3] sums to 7)

Visual Walkthrough

[2, 3, 1, 2, 4, 3]  target=7
 ↑
 L,R  sum=2 (too small, expand)

[2, 3, 1, 2, 4, 3]
 ↑  ↑
 L  R  sum=5 (too small, expand)

[2, 3, 1, 2, 4, 3]
 ↑     ↑
 L     R  sum=6 (too small, expand)

[2, 3, 1, 2, 4, 3]
 ↑        ↑
 L        R  sum=8 β‰₯7 βœ“ (size=4, shrink!)

[2, 3, 1, 2, 4, 3]
    ↑     ↑
    L     R  sum=6 (too small, expand)

[2, 3, 1, 2, 4, 3]
    ↑        ↑
    L        R  sum=10 β‰₯7 βœ“ (size=4, shrink!)

... continue until [4,3] with size=2 βœ“

Java Code

int minSubArrayLen(int target, int[] nums) {
    int left = 0;
    int sum = 0;
    int minLen = Integer.MAX_VALUE;

    for (int right = 0; right < nums.length; right++) {
        sum += nums[right];  // Expand

        while (sum >= target) {
            minLen = Math.min(minLen, right - left + 1);
            sum -= nums[left];  // Shrink
            left++;
        }
    }

    return minLen == Integer.MAX_VALUE ? 0 : minLen;
}

Memory Trick

Expand when sum is too small. Shrink when sum is big enough. Always keep the smallest valid window!


πŸ”οΈ Pattern 4: Sliding Window Maximum

The Problem

Given an array and window size k, find the maximum element in each window position.

Example

Array: [1, 3, -1, -3, 5, 3, 6, 7]
k = 3

Window positions β†’ Maximum:
[1, 3, -1]        β†’ 3
[3, -1, -3]       β†’ 3
[-1, -3, 5]       β†’ 5
[-3, 5, 3]        β†’ 5
[5, 3, 6]         β†’ 6
[3, 6, 7]         β†’ 7

Output: [3, 3, 5, 5, 6, 7]

The Deque Trick

We use a deque (double-ended queue) to keep track of useful elements:

graph TD A["Deque stores INDICES"] A --> B["Front = index of current max"] B --> C["Always decreasing order"] C --> D["Remove smaller elements"] D --> E["Remove out-of-window elements"]

Why Deque?

Without deque: O(n Γ— k) - check all k elements each time
With deque:    O(n)     - each element enters/exits once

Java Code

int[] maxSlidingWindow(int[] nums, int k) {
    if (nums.length == 0) return new int[0];

    int n = nums.length;
    int[] result = new int[n - k + 1];
    Deque<Integer> dq = new ArrayDeque<>();

    for (int i = 0; i < n; i++) {
        // Remove indices outside window
        while (!dq.isEmpty() && dq.peekFirst() < i - k + 1) {
            dq.pollFirst();
        }

        // Remove smaller elements (useless)
        while (!dq.isEmpty() && nums[dq.peekLast()] < nums[i]) {
            dq.pollLast();
        }

        dq.offerLast(i);  // Add current index

        // Record result when window is full
        if (i >= k - 1) {
            result[i - k + 1] = nums[dq.peekFirst()];
        }
    }

    return result;
}

Visual Deque Logic

Array: [1, 3, -1, -3, 5, 3, 6, 7], k=3

i=0: add 1  β†’ deque=[0]
i=1: 3>1, remove 1, add 3 β†’ deque=[1]
i=2: -1<3, add -1 β†’ deque=[1,2], max=3 βœ“
i=3: -3<-1, add -3 β†’ deque=[1,2,3], max=3 βœ“
i=4: 5>all, clear & add 5 β†’ deque=[4], max=5 βœ“
i=5: 3<5, add 3 β†’ deque=[4,5], max=5 βœ“
i=6: 6>3, remove 3, 6>5, remove 5, add 6 β†’ deque=[6], max=6 βœ“
i=7: 7>6, remove 6, add 7 β†’ deque=[7], max=7 βœ“

πŸŽ“ Quick Comparison

Pattern Window Size Goal Key Trick
Fixed Size Constant Find sum/avg Add front, remove back
Variable Size Changes Find min/max length Expand & shrink
Min Subarray Sum Variable Smallest β‰₯ target Shrink while valid
Sliding Maximum Fixed Max per window Deque (decreasing)

πŸš€ When to Use Sliding Window?

Ask yourself:

  1. Contiguous subarray? β†’ Sliding Window candidate
  2. Fixed size? β†’ Fixed Window Pattern
  3. Find min/max length? β†’ Variable Window Pattern
  4. Track max/min in windows? β†’ Deque Pattern

🧠 Golden Rules

1. Never look back unnecessarily
   β†’ Add new, remove old in O(1)

2. Two pointers move in ONE direction
   β†’ Left never goes past right

3. Track what matters
   β†’ Sum, count, or maxβ€”update as you slide

4. Shrink when possible
   β†’ For variable windows, always try to minimize

πŸŽ‰ You Made It!

You now understand the four core sliding window patterns:

  1. Fixed Size - The photo frame approach
  2. Variable Size - The rubber band approach
  3. Minimum Subarray Sum - Expand then shrink
  4. Sliding Window Maximum - The clever deque

These patterns solve hundreds of interview questions. Practice them, and they’ll become second nature!

β€œEvery master was once a beginner. Every pro was once confused. Keep sliding forward!” πŸͺŸ

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.