DEV Community

Quipoin
Quipoin

Posted on

Sliding Window on Strings Explained Simply in Java


Many string problems look complicated because they involve:

  • substrings
  • repeated characters
  • dynamic conditions

Beginners often use nested loops…

But sliding window reduces many of these problems from:

  • O(n²) to:
  • O(n)

1. Longest Substring Without Repeating Characters
Problem

Find the length of the longest substring with unique characters.

Efficient Sliding Window Solution

public static int lengthOfLongestSubstring(String s) {

Set<Character> set = new HashSet<>();

int left = 0, maxLen = 0;

for (int right = 0; right < s.length(); right++) {

    while (set.contains(s.charAt(right))) {

        set.remove(s.charAt(left));

        left++;
    }

    set.add(s.charAt(right));

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

return maxLen;
Enter fullscreen mode Exit fullscreen mode

}

Core Idea

Maintain a window:

  • expand right pointer
  • shrink left when duplicate appears

This keeps the substring valid.

*2. Minimum Window Substring
*
Problem

Find the smallest substring containing all characters of a pattern.

Example:

Text = "ADOBECODEBANC"
Pattern = "ABC"

Answer:

"BANC"

Key Idea

Use:

  • character frequency counts
  • dynamic window resizing

Expand until valid,
then shrink to minimize window.

3. Longest Repeating Character Replacement
Problem

Given:

  • a string
  • k replacements

Find the longest substring that can become all same characters.

Smart Observation

Track:

  • most frequent character inside window.

If:

windowSize - maxFreq > k

then shrink window.

Sliding window works because:

  • we reuse previous computations instead of recalculating substrings.

That’s the optimization.

  • Sliding window avoids nested loops
  • Expand → valid state
  • Use two pointers
  • Track characters using set/map
  • Expand right pointer
  • Shrink left when condition breaks
  • Complexity → O(n)

Sliding window is one of the most important interview patterns.

Once you master it,

  • many “hard” string problems become manageable

Explore More: https://www.quipoin.com/tutorial/data-structure-with-java/sliding-window-on-strings

Top comments (0)