Sliding Window Technique in DSA

What is the Sliding Window Technique?

The Sliding Window Technique is an optimization strategy for problems involving linear data structures like arrays or strings. It helps reduce the time complexity from O(n²) to O(n) in many cases by avoiding unnecessary re-computation.

Instead of recalculating results for every subarray or substring, we "slide" a window across the structure — updating the result incrementally.

When to Use

Types of Sliding Windows

1. Fixed-size Sliding Window

You know the window size (say k), and the goal is to perform operations over every subarray of size k.

Common Example:

Find the maximum sum of any subarray of size k.

Pseudocode

class SlidingWindowFixed {
    function maxSum(arr, k):
        n = length(arr)
        windowSum = sum of first k elements
        maxSum = windowSum

        for i = k to n-1:
            windowSum = windowSum + arr[i] - arr[i - k]
            maxSum = max(maxSum, windowSum)

        return maxSum
}

Time and Space Complexity

2. Variable-size Sliding Window

Window size changes dynamically based on the conditions. You expand the window by moving the right pointer and shrink it by moving the left pointer until conditions are satisfied.

Common Example:

Find the length of the longest substring with at most K distinct characters.

Pseudocode

class SlidingWindowVariable {
    function longestSubstringWithKDistinct(s, k):
        left = 0
        right = 0
        freqMap = {}
        maxLen = 0

        while right < length(s):
            add s[right] to freqMap
            while size of freqMap > k:
                decrement freqMap[s[left]]
                if freqMap[s[left]] == 0:
                    remove s[left] from freqMap
                left += 1
            maxLen = max(maxLen, right - left + 1)
            right += 1

        return maxLen
}

Time and Space Complexity

Real-World Applications

Example 1: Longest Substring with K Unique Characters

Problem Statement:

Given a string s and an integer k, find the length of the longest substring that contains exactly k unique characters.

For example:

Why Sliding Window?

Using a sliding window is efficient for problems that require processing substrings or subarrays. Instead of generating all substrings and checking each, we maintain a dynamic window with exactly k unique characters and slide it to explore new substrings.

Step-by-step Sliding Window Approach:

  1. Initialize two pointers: left and right for the sliding window.
  2. Use a hash map charCount to count characters in the window.
  3. Expand the window by moving right and updating charCount.
  4. If unique characters exceed k, shrink the window by moving left.
  5. Update the result whenever exactly k unique characters are found.

Pseudocode

// Function to find longest substring with k unique characters
function longestKUniqueSubstring(s, k):
    left = 0
    right = 0
    maxLen = 0
    charCount = empty map

    while right < length of s:
        // Add current character to map
        charCount[s[right]] += 1

        // If unique characters > k, shrink window
        while size of charCount > k:
            charCount[s[left]] -= 1
            if charCount[s[left]] == 0:
                remove s[left] from charCount
            left += 1

        // If exactly k unique characters, update maxLen
        if size of charCount == k:
            maxLen = max(maxLen, right - left + 1)

        right += 1

    return maxLen

Why It Works:

This approach dynamically adjusts the window and ensures that we are always considering substrings with at most k unique characters. When exactly k are present, we update the maximum length seen so far.

Time Complexity:

Space Complexity:

Sliding window techniques like this are crucial in substring problems where the window size or character frequency needs to be tracked. It’s much more efficient than brute-force methods and can be easily adapted to variations of the problem.

Benefits of Sliding Window

Limitations

Conclusion

The Sliding Window technique is a must-know strategy for solving linear structure problems efficiently. It transforms brute-force nested loop solutions into linear-time solutions by reusing previous computations. Mastering fixed and variable window problems unlocks a broad class of optimization problems in DSA interviews and competitive programming.