← Back to Index

πŸ” Sliding Window – Java Cheat Sheet (One Page)

πŸ“Œ What Is It?

Sliding Window is a technique to reduce time complexity for problems involving subarrays or substrings. Instead of nested loops, we β€œslide” a window across the input.

🧱 Pattern Template (Fixed Size)

int sum = 0;
for (int i = 0; i < nums.length; i++) {
    sum += nums[i];
    if (i >= k - 1) {
        max = Math.max(max, sum);
        sum -= nums[i - k + 1];
    }
}

🧱 Pattern Template (Variable Size)

int left = 0;
for (int right = 0; right < s.length(); right++) {
    // expand window by including s.charAt(right)

    while (window is invalid) {
        // shrink window from left
        left++;
    }

    if (window is valid) {
        // update result
    }
}

βœ… Use Cases

πŸ“˜ Common LeetCode Problems

πŸ§ͺ Example: Max Sum of Size k

int maxSum = 0, windowSum = 0;
for (int i = 0; i < nums.length; i++) {
    windowSum += nums[i];
    if (i >= k - 1) {
        maxSum = Math.max(maxSum, windowSum);
        windowSum -= nums[i - k + 1];
    }
}

🎬 Watch Minimum Window Subsequence Animation

🎬 Watch Sliding Window Maximum Animation

πŸ’‘ Pro Tips