2Brute2Best
🔥0
01

Fixed Window (Sliding Window Sub-pattern)

The window size is given and never changes. You never decide when to shrink — every step you add one element on the right and remove one on the left.

Signals in the problem statement
  • ›

    "subarray of size k"

  • ›

    "k consecutive elements"

  • ›

    "every window of length k"

  • ›

    "anagram / permutation of p" (window size = length of p)

What makes it different

No validity check and no while loop. The only job is to keep the aggregate (sum, counts) correct as the window slides.

Questions

ordered from “learn the idea” to “recognise it without help”
  1. 1
    Maximum Sum Subarray of Size K
    Basic Anchor·GeeksforGeeks
    Easy
  2. 2
    Maximum Average Subarray I
    Basic Reinforcement·LeetCode #643
    Easy
  3. 3Medium
  4. 4
    Permutation in String
    Medium·LeetCode #567
    Medium
  5. 5
    Find All Anagrams in a String
    Pattern Transfer·LeetCode #438
    Medium
  6. 6
    Maximum Points You Can Obtain from Cards
    Interview-Level·LeetCode #1423
    Medium
  7. 7
    Maximum Sum of Distinct Subarrays With Length K
    Tricky / Edge Case·LeetCode #2461
    Medium

Template

fixed-template.cpp
// Fixed window of size k: add the element entering, remove the element leaving.
long long fixedWindow(vector<int>& a, int k) {
    long long window = 0, best = LLONG_MIN;
    for (int right = 0; right < (int)a.size(); right++) {
        window += a[right];                 // 1. element enters on the right
        if (right >= k) window -= a[right - k]; // 2. element leaves on the left
        if (right >= k - 1) best = max(best, window); // 3. window is full: use it
    }
    return best;
}
Remember this · Sliding Window
Trigger
Contiguous subarray / substring + longest, shortest, maximum, count, or "of size K".
Think
Can I keep a valid range and move it, instead of checking every subarray from scratch?
Key question
When is my current window valid?