Sliding Window and Pattern - (Theory)


What is the Sliding Window Technique?

The Sliding Window Technique is an algorithmic approach used to solve problems that require examining all contiguous subarrays or substrings of a given size or range in a linear structure like arrays or strings.

This technique involves moving a “window” across the input data to keep track of specific properties (like sum, max, frequency) without reprocessing the entire window after every move.

Key Benefits:


Relation to the Two Pointers Technique

The Sliding Window Technique is conceptually derived from the Two Pointers Technique.

Two Pointers Basics:

How Sliding Window Extends Two Pointers:


Core Sliding Window Patterns

The technique can be categorized into three core patterns based on the window behavior and constraint types.


1. Fixed Size Sliding Window

Definition:

Used when the window size is constant (usually given as k in the problem).

Typical Use Cases:

Algorithm Logic:

Time and Space Complexity:

Example: Maximum Sum Subarray of Size K

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

2. Variable Size Sliding Window

This pattern is used when the window size changes dynamically depending on a condition.

There are two subtypes:


(a) Variable Size - Condition Based Only

Used when the condition is based on numerical thresholds or cumulative properties (like sum), without needing a hashmap or set.

Use Cases:

Algorithm Logic:

Time and Space Complexity:

Example: Minimum Subarray Length With Sum ≥ Target

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

(b) Variable Size - Condition Based with Hash Table or Hash Set

Used when you must track the frequency, uniqueness, or count of specific elements within the window.

Use Cases:

Algorithm Logic:

Time and Space Complexity:

Example: Longest Substring Without Repeating Characters

public int lengthOfLongestSubstring(String s) {
    Set<Character> seen = new HashSet<>();
    int start = 0, maxLen = 0;
    for (int end = 0; end < s.length(); end++) {
        while (seen.contains(s.charAt(end))) {
            seen.remove(s.charAt(start++));
        }
        seen.add(s.charAt(end));
        maxLen = Math.max(maxLen, end - start + 1);
    }
    return maxLen;
}

Summary Table of Sliding Window Patterns

Pattern Key Use Case Time Complexity Space Complexity HashMap/Set Used
Fixed Size Sum/Max/Min of fixed-size subarrays O(n) O(1) or O(k) No
Variable Size - Condition Based Sum constraints (e.g., sum ≥ target) O(n) O(1) No
Variable Size - With Lookup Uniqueness, frequencies, character windows O(n) O(n) Yes

Advanced Sliding Window Variations

In addition to the three core types, the following are advanced and specialized applications of the sliding window.


3. Sliding Window with Deque (Monotonic Queue)

Description:

Used to maintain elements in order (increasing or decreasing) for max/min queries in each window.

Use Case:

Time and Space Complexity:


Description:

Used when you cannot directly determine the validity of a window in O(1) and must apply binary search on the window size.

Use Case:

Time and Space Complexity:


5. Circular Sliding Window

Description:

Used when the array wraps around (circular structure). You can simulate this with an extended array or modulo indexing.

Use Case:


When to Use Sliding Window Technique

Ask yourself these questions:

  1. Are you dealing with contiguous elements in an array or string?

  2. Are you interested in properties like sum, max, frequency, or uniqueness over a range?

  3. Can the required property be maintained incrementally as the window slides?

  4. Is brute-force giving you O(n²) complexity and you need optimization?


Checklist for Solving Sliding Window Problems


Conclusion

The sliding window technique is one of the most powerful and versatile tools in algorithm design. With a solid grasp of its fixed and variable size patterns, and the ability to integrate auxiliary structures like hash tables and deques, you can approach a wide range of problems with optimal efficiency.

Quick Recap: