Algorithmsvariable sliding window
Variable Sliding Window (Dynamic Adjustment Based on Conditions)
TT
Testlaa Team
May 14, 2026•1 min read
Variable windows change width based on a predicate—for example “at most K distinct characters” or “sum ≤ budget.” You grow R while valid, then shrink L until valid again.
Why this shows up in the real world
Adaptive bitrate streaming widens the buffer window when bandwidth is good and tightens when congestion hits. Loan underwriting might accept any contiguous employment history window that crosses a minimum months threshold—variable extraction.
Core idea (explained for students)
Typical loop: R from 0..n-1, add a[R] into state, while not valid(L,R): remove a[L], L++. Answer might be max length of valid window, count of windows, etc.
Try this in Python
from collections import Counter
def longest_k_distinct(s: str, k: int) -> int:
ct, best, L = Counter(), 0, 0
for R, ch in enumerate(s):
ct[ch] += 1
while len(ct) > k:
ct[s[L]] -= 1
if ct[s[L]] == 0:
del ct[s[L]]
L += 1
best = max(best, R - L + 1)
return best
print(longest_k_distinct("eceba", 2))
Common mistakes
- Infinite loops if your validity check never progresses
L. - Forgetting to update state when
Lmoves. - Off-by-one when the empty window should or should not be considered.
Key takeaways
- Variable window = while invalid: shrink from left.
- Symmetric variants shrink from right—mirror the logic carefully.
Tags:
Sliding windowPythonStudents
