sliding window.png

Before diving into the pattern, let me give you a quick intro. I'm a Information Science student and a competitive programmer. Over time, as I practiced problems in contests and interviews, I began to see patterns—especially in problems dealing with sequences. One of the most effective and commonly used patterns is Sliding Window.

Sliding Window is a technique typically used for problems involving subarrays or substrings. It allows you to avoid unnecessary repeated computations by maintaining a window over a portion of the data and sliding it forward as needed, keeping track of required information dynamically.

Let’s walk through the pattern and highlight key points along with some classic problems.

Problem Statement
Given an array or string, find the maximum/minimum/number of something in a subarray/substring of fixed or variable length.

Approach
Maintain a window of size k (fixed) or use two pointers to create a dynamic-sized window.

Slide the window by adding the new element and removing the old one while updating the result accordingly.

Use auxiliary data structures like a queue or hash map when needed (e.g., for character count, frequency).

Java Template (Fixed-Length Window)

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

Java Template (Variable-Length Window)

public int minSubArrayLen(int target, int[] nums) {
    int left = 0, sum = 0, minLen = Integer.MAX_VALUE;
    for (int right = 0; right < nums.length; right++) {
        sum += nums[right];
        while (sum >= target) {
            minLen = Math.min(minLen, right - left + 1);
            sum -= nums[left++];
        }
    }
    return minLen == Integer.MAX_VALUE ? 0 : minLen;
}

Similar Problems

ProblemDifficultyLink
209. Minimum Size Subarray SumMedium🔗
3. Longest Substring Without Repeating CharactersMedium🔗
1004. Max Consecutive Ones IIIMedium🔗
76. Minimum Window SubstringHard🔗
438. Find All Anagrams in a StringMedium🔗
424. Longest Repeating Character ReplacementMedium🔗
567. Permutation in StringMedium🔗
2958. Length of Longest Subarray With at Most K FrequencyMedium🔗
239. Sliding Window MaximumHard🔗
30. Substring with Concatenation of All WordsHard🔗
Comments (0)