dsa2 min read

Sliding Window Technique from Scratch (2026)

Sliding Window Technique from Scratch (2026)

Published:  |  Category: Dsa  |  Reading time: ~15 min
Sliding Window Technique from Scratch (2026)

The sliding window technique efficiently processes arrays by maintaining a dynamic window of elements and updating it incrementally instead of recomputing from scratch. It reduces time complexity from O(n²) to O(n) for many substring/subarray problems.

Windows are classified as fixed-size (constant length) or variable-size (shrinking/expanding based on constraints). The technique is essential for substring problems involving sums, averages, or character frequencies.

Fixed-Size Sliding Window

For a window of fixed size k, compute the initial window value (sum, average, or any aggregate). Then slide by one position: subtract the outgoing element and add the incoming element. Update the running result as needed.

This approach handles problems like maximum sum subarray of size k, first negative integer in every window, and count occurrences of anagrams in O(n) time.

int maxSumFixedWindow(vector& arr, int k) {
    int n = arr.size();
    if (n < k) return -1;
    int windowSum = 0;
    for (int i = 0; i < k; i++) windowSum += arr[i];
    int maxSum = windowSum;
    for (int i = k; i < n; i++) {
        windowSum += arr[i] - arr[i - k];
        maxSum = max(maxSum, windowSum);
    }
    return maxSum;
}

Variable-Size Sliding Window

Variable-size windows expand and contract based on a condition (e.g., sum ≤ target, contains all required characters). The right pointer expands the window, while the left pointer shrinks it when the condition is violated or to find the minimum valid window.

This pattern solves longest substring without repeating characters, minimum window substring, and subarray sum problems efficiently.

int longestSubstringWithoutRepeating(string s) {
    vector lastIndex(256, -1);
    int left = 0, maxLen = 0;
    for (int right = 0; right < s.size(); right++) {
        if (lastIndex[s[right]] >= left)
            left = lastIndex[s[right]] + 1;
        lastIndex[s[right]] = right;
        maxLen = max(maxLen, right - left + 1);
    }
    return maxLen;
}

Frequently Asked Questions

When should I use fixed vs variable sliding window?

Use fixed window when the window size is constant (e.g., sum of every k-sized subarray). Use variable window when you need to find the smallest/longest window satisfying a dynamic constraint.

What is the time complexity of sliding window?

Sliding window achieves O(n) time because each element is visited at most twice—once when entering the window (right pointer) and once when leaving (left pointer).

Originally published on Ayodhyyya. Last updated June 1, 2026.