DEV Community

Dev Cookies
Dev Cookies

Posted on

๐Ÿ” Sliding Window Technique in Java โ€“ The Ultimate Guide ๐Ÿšช

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
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿงฉ 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
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”จ 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;
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿง  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;
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿง  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;
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿง  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;
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿงฎ 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

Top comments (0)