Sliding Window is a powerful technique used for solving problems that involve arrays or strings where you need to examine contiguous subarrays (or substrings) efficiently.

It helps reduce O(n²) time complexity to O(n) in many scenarios.


🧠 What is the Sliding Window Technique?

The Sliding Window technique involves moving a window (range) over your input data structure to track a subset of elements that satisfy a condition — such as sum, max/min, or uniqueness.

There are two types:

  • Fixed-size Window (size is constant)
  • Variable-size Window (size grows or shrinks based on conditions)

🔥 When to Use It?

✅ Subarray or substring problems

✅ Optimize brute-force nested loops

✅ Continuous or sliding segment problems

✅ Max/min/avg/sum/unique patterns


✨ Sliding Window Templates

🧩 Fixed-size window

for (int i = 0; i < n; i++) {
    // Expand the window
    window.add(nums[i]);

    // Once window size is reached
    if (i >= k - 1) {
        result = ... // Do something
        window.remove(nums[i - k + 1]); // Slide the window
    }
}

🧩 Variable-size window

int left = 0;

for (int right = 0; right < n; right++) {
    // Expand to right

    while (condition is violated) {
        // Shrink from left
        left++;
    }

    // Update answer if needed
}

🔨 Java Code Examples


📘 1. Maximum Sum Subarray of Size K

public int maxSum(int[] nums, int k) {
    int max = 0, windowSum = 0;

    for (int i = 0; i < nums.length; i++) {
        windowSum += nums[i];

        if (i >= k - 1) {
            max = Math.max(max, windowSum);
            windowSum -= nums[i - k + 1];
        }
    }
    return max;
}

🧠 Fixed-size sliding window

⏱ Time: O(n)


📘 2. Longest Substring Without Repeating Characters

public int lengthOfLongestSubstring(String s) {
    Set<Character> set = new HashSet<>();
    int left = 0, max = 0;

    for (int right = 0; right < s.length(); right++) {
        while (set.contains(s.charAt(right))) {
            set.remove(s.charAt(left++));
        }
        set.add(s.charAt(right));
        max = Math.max(max, right - left + 1);
    }

    return max;
}

🧠 Variable-size window

⏱ Time: O(n)


📘 3. Minimum Size Subarray Sum

Given nums[] and target, find the minimum length of subarray whose sum ≥ target.

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;
}

🧠 Shrinking window when condition met

⏱ Time: O(n)


📘 4. Longest Repeating Character Replacement

Replace at most k characters to get the longest substring with the same character.

public int characterReplacement(String s, int k) {
    int[] count = new int[26];
    int left = 0, maxFreq = 0, maxLen = 0;

    for (int right = 0; right < s.length(); right++) {
        count[s.charAt(right) - 'A']++;
        maxFreq = Math.max(maxFreq, count[s.charAt(right) - 'A']);

        while (right - left + 1 - maxFreq > k) {
            count[s.charAt(left++) - 'A']--;
        }

        maxLen = Math.max(maxLen, right - left + 1);
    }

    return maxLen;
}

🧮 Time & Space Complexity

Problem Time Complexity Space Complexity
Max sum subarray O(n) O(1)
Longest substring w/o repeats O(n) O(n)
Min subarray sum ≥ target O(n) O(1)

📦 Comparison with Brute Force

Brute-force Sliding Window
O(n²) O(n)
Inefficient Optimal
Nested loops Single loop

💡 Real Interview Problems That Use It

Problem Platform
Longest Substring Without Repeating LeetCode 3
Minimum Window Substring LeetCode 76
Sliding Window Maximum LeetCode 239
Permutation in String LeetCode 567
Longest Repeating Char Replacement LeetCode 424

🎯 Final Words

The Sliding Window technique is a must-know for any aspiring software engineer. It turns brute-force time-consuming solutions into sleek and elegant O(n) solutions. 🚀


🔁 Related Concepts

  • Two Pointer Technique 🏃‍♂️🏃‍♀️
  • Prefix Sum
  • Monotonic Queue
  • HashMap and Frequency Counters