DSA · Intermediate · Pattern 1 of 10
Sliding Window
14 problems.
Your progress0%
- 1st Visit
- 0/14
- 2nd Visit
- 0/14
- Revise
- 0/14
About this pattern
A sliding window maintains a contiguous range [l, r] and updates a summary of it (a sum, a frequency table, a count of distinct items) incrementally as the right end advances and the left end catches up. Fixed-size windows move both ends together; variable-size windows extend r and then shrink l until a condition is restored.
Signals: the statement asks for the longest, the shortest or the number of contiguous subarrays or substrings that satisfy a constraint, and the constraint stays valid when the window shrinks. Since each index enters and leaves the window once, the scan is O(n) plus the cost of updating the summary.
// Longest window whose condition can be restored by shrinking.
int best = 0;
unordered_map<char, int> cnt; // window summary
for (int l = 0, r = 0; r < (int)s.size(); ++r) {
cnt[s[r]]++; // extend right
while (windowInvalid(cnt)) { // shrink left until valid
if (--cnt[s[l]] == 0) cnt.erase(s[l]);
++l;
}
best = max(best, r - l + 1);
}