Sliding window
A sliding window maintains a contiguous slice of a sequence as two ends move only forward. Each element enters and leaves the window at most once, so a class of subarray problems that look O(n²) become O(n).
Detailed Explanation
You want the longest substring with at most k distinct characters, or the shortest subarray whose sum is at least s. The naive approach starts at every index and extends to the right. A sliding window keeps a [left, right) slice, extends right when the window is still valid (or until it becomes valid), and advances left when the window breaks the constraint. Because both ends only increase, the total work is linear.
The window is the invariant: "this slice is the current candidate, and I have a running summary of it" — a sum, a count of distinct keys, a frequency map, a deque of maxima. Updating the summary when an element enters or leaves must be O(1) or O(log n), or you have not beaten the nested loop.
Fixed-length windows are the simple case: a window of size k, slide by one, update the sum by adding a[i] and subtracting a[i-k]. Variable-length windows need a rule for when to shrink. Typical rules: shrink while the sum is too large, shrink while too many unique characters, shrink while a required character count is satisfied (minimum window substring).
A deque of indices stores candidates for "maximum in the window" in decreasing order. The front is the max. Pop the front when it leaves the window. Pop the back when the new element is larger. That is O(n) for all window maxima.
C++ tools: two size_t indices into a vector or string, or a std::deque for the max trick, or an unordered_map for frequencies. string_view can name the current window without copying: string_view(s).substr(left, right - left) — but substr on string allocates, so prefer indices or string_view from the start.
Not every subarray problem is a window. If the constraint is not monotonic (extending the window can make a bad window good again in a non-structured way), you cannot only move left forward. Need a different structure (prefix sums plus a map, or DP).
Empty windows, k == 0, and k > n are the usual edges. Use signed accumulators if the sum can be negative; "shortest subarray with sum ≥ s" with negatives is not a vanilla shrinkable window.
Code Examples
#include <iostream>
#include <vector>
int maxSumWindow(const std::vector<int>& a, std::size_t k) {
int sum = 0;
for (std::size_t i = 0; i < k; ++i) sum += a[i];
int best = sum;
for (std::size_t i = k; i < a.size(); ++i) {
sum += a[i] - a[i - k];
if (sum > best) best = sum;
}
return best;
}
int main() {
std::vector<int> a{2, 1, 5, 1, 3, 2};
std::cout << maxSumWindow(a, 3) << '\n'; // prints: 9 (5+1+3)
}#include <algorithm>
#include <iostream>
#include <string>
#include <unordered_map>
int longestAtMostK(const std::string& s, int k) {
std::unordered_map<char, int> freq;
int distinct = 0, best = 0, left = 0;
for (int right = 0; right < static_cast<int>(s.size()); ++right) {
if (freq[s[right]]++ == 0) ++distinct;
while (distinct > k) {
if (--freq[s[left]] == 0) --distinct;
++left;
}
best = std::max(best, right - left + 1);
}
return best;
}
int main() {
std::cout << longestAtMostK("eceba", 2) << '\n'; // prints: 3 ("ece")
}Common Gotchas
Shrinking a window when the property is not monotonic
negative numbers break "sum ≥ s" shrinking. Use prefix sums.
`freq[c]++` inserts keys
for a `map`, that is fine. Erase keys when the count hits 0 if you use `freq.size()` as distinct count.
Each index moves at most once
if you write a nested loop that resets `left` to 0, you no longer have a sliding window.