Sliding Window
A sliding window maintains a contiguous slice of an array that grows or shrinks as you scan. Each element enters and leaves the window at most once, so a class of subarray problems that look O(n^2) become O(n).
Detailed Explanation
You want the longest substring without repeating characters, the shortest subarray whose sum is at least s, the maximum in every window of width k. The brute force enumerates every pair (l, r). The window keeps one pair and moves r forward, then moves l forward only when the invariant breaks.
The invariant is a property of a[l .. r]: "sum is at most s," "all characters unique," "exactly k distinct keys." When you add a[r] and the property fails, you remove a[l] until it holds again. Because l and r only increase, the inner removals amortize to O(n).
Fixed-width windows are simpler. r goes from k-1 to n-1, and you add a[r] and subtract a[r-k]. A running sum, a running XOR, or a deque of candidates for the window maximum all fit this shape.
C implementation is two size_t indices and whatever extra structure the invariant needs: an integer sum, a count[256] for bytes, a hash table of frequencies. The extra structure must be updated on both enter and leave. Forgetting the leave is how the window silently includes items it already passed.
The technique needs a sequence you can index or walk once. It does not apply to a set of unrelated items. It does not apply when any subarray, not just a contiguous one, is allowed — that is a subset problem and usually DP or meet-in-the-middle.
Negative numbers break some sum-window arguments. If adding an element can make the sum both worse and better later, "shrink while too big" is no longer safe. Then you want prefix sums plus a structure that queries range sums, or a different algorithm.
Code Examples
#include <stdio.h>
/* Longest window whose sum is <= limit. Assumes non-negative a[i]. */
static int longest_at_most(const int *a, int n, int limit)
{
int left = 0, sum = 0, best = 0;
for (int right = 0; right < n; right++) {
sum += a[right];
while (left <= right && sum > limit) {
sum -= a[left];
left++;
}
if (right - left + 1 > best) {
best = right - left + 1;
}
}
return best;
}
int main(void)
{
int a[] = { 1, 2, 3, 1, 1 };
printf("%d\n", longest_at_most(a, 5, 5)); /* prints: 3 (3+1+1) */
return 0;
}#include <stdio.h>
static void window_sums(const int *a, int n, int k)
{
if (k <= 0 || k > n) {
return;
}
int sum = 0;
for (int i = 0; i < k; i++) {
sum += a[i];
}
printf("%d ", sum);
for (int i = k; i < n; i++) {
sum += a[i] - a[i - k];
printf("%d ", sum);
}
printf("\n");
}
int main(void)
{
int a[] = { 1, 2, 3, 4 };
window_sums(a, 4, 2); /* prints: 3 5 7 */
return 0;
}Common Gotchas
Negative values can invalidate "shrink when the sum is too large"
the next element might need those negatives. Restrict the proof, or change algorithm.
Updating the running state on `right` but not on `left` double-counts
every enter has a leave.
A window is contiguous
if the problem says subsequence, this is the wrong tool.
`count[256]` only works for bytes
Unicode code points need a real map.