🪟 Sliding Window Technique

Sliding Window is a fundamental technique used for solving problems involving contiguous subarrays or substrings. It optimizes problems that would otherwise require nested loops by maintaining a dynamic window that expands and contracts based on a condition.

📑 Table of Contents

  1. Overview & Keywords
  2. Types of Sliding Window
  3. Core Templates
  4. Key Patterns
  5. Practice Problems

Overview & Keywords

Common problem indicators:


Types of Sliding Window

1️⃣ Fixed-Size Window (size = K)

Use when window size is constant.

Common Use Cases:

2️⃣ Variable-Size Window (Stretch/Shrink)

Use when window grows and shrinks dynamically based on a condition.

Common Use Cases:


Core Templates

🔶 Template 1: Fixed Size Window

int left = 0;
long long sum = 0, best = 0;

for (int right = 0; right < n; right++) {
    sum += arr[right]; // expand window

    if (right - left + 1 == K) {
        best = max(best, sum); // process window
        sum -= arr[left]; // shrink
        left++;
    }
}

🔶 Template 2: Variable Window (Universal)

int left = 0;
for (int right = 0; right < n; right++) {
    // Add arr[right] to window

    while (window_condition_invalid) {
        // Shrink window from left
        left++;
    }

    // Update answer with current window [left, right]
}

🔶 Template 3: Frequency Map (Substring Problems)

unordered_map<char, int> freq;
int left = 0;

for (int right = 0; right < s.size(); right++) {
    freq[s[right]]++;

    while (condition_invalid) {
        freq[s[left]]--;
        if (freq[s[left]] == 0) freq.erase(s[left]);
        left++;
    }

    ans = max(ans, right - left + 1);
}

Key Patterns

Pattern Condition Trigger Use When
No Repeating Any char count > 1 Shrink until all freq = 1 Longest substring without repeating chars
At Most K Distinct freq_map.size() > K Shrink until size ≤ K Max subarray with ≤ K distinct elements
Sum ≤ Target sum > target Shrink until sum ≤ target Min subarray, max subarray with constraint
Two Hash Maps Elements not in target Shrink while valid Minimum window substring
Fixed Size window size = K Always process at size K Fixed window problems

Practice Problems

📋 Level 1 — Fundamentals

📋 Level 2 — Medium

📋 Level 3 — Advanced


← Back to Arrays DSA Hub 🏠