The sliding window technique reuses work from the previous step instead of recomputing it. Moving a window one step at a time turns many nested-loop problems into a single pass.
Why Recomputing Every Window Is Slow
What is the Sliding Window Technique?
The Sliding Window Technique maintains a contiguous range (the window) over an array or string. As the window moves forward, we update the result incrementally, reusing the previous window’s state instead of recomputing it.
Key advantages:
- O(n) time for many problems that would otherwise be O(n²) or O(n × k).
- O(1) extra space in the fixed-size case.
- Simple, uniform pattern applicable to arrays, strings, and streams.
Why Sliding Windows Matter
- Subarray sum problems: Maximum sum of size
k, smallest subarray with sum ≥ target. - String problems: Longest substring without repeating characters, anagram matching.
- Streaming data: Smoothing, moving averages, rate limiting.
- Interview preparation: Extremely common pattern.
- Performance: Turns quadratic solutions into linear ones.
Two Types of Sliding Window
| Type | When to Use | Example Problem |
|---|---|---|
| Fixed Size | Window size k is given | Max sum of subarray of size k |
| Variable Size | Window size depends on a condition | Longest substring without repeats |
Identifying Sliding Window Problems
Ask yourself:
- Does the problem involve subarrays or substrings?
- Is there a maximum/minimum or longest/shortest to find?
- Is there a constraint (sum ≥ k, no repeats, distinct elements ≤ k)?
If yes, sliding window is likely the right pattern.
Fixed and Variable Window Patterns
Fixed-Size Sliding Window
Steps:
- Compute the sum (or metric) of the first
kelements. - Slide the window one step:
window_sum += arr[i] - arr[i - k]. - Track the maximum (or minimum) across all windows.
#include <stdio.h>
#include <limits.h>
int maxSumFixedK(const int arr[], int n, int k) {
if (n < k || k <= 0) return -1;
long long windowSum = 0;
for (int i = 0; i < k; i++) windowSum += arr[i];
long long maxSum = windowSum;
for (int i = k; i < n; i++) {
windowSum += arr[i] - arr[i - k];
if (windowSum > maxSum) maxSum = windowSum;
}
return (int)maxSum;
}
int main(void) {
int arr[] = {5, 2, -1, 0, 3};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3;
printf("%d\n", maxSumFixedK(arr, n, k));
return 0;
}
Expected output:
6
Time: O(n), Space: O(1)
Variable-Size Sliding Window
Steps:
- Use
leftandrightpointers starting at 0. - Expand
rightuntil the condition is violated. - Shrink
leftuntil the condition holds again. - Track the optimum window along the way.
Example: Longest substring without repeating characters.
#include <stdio.h>
#include <string.h>
int longestUniqueSubstr(const char *s) {
int lastSeen[256];
for (int i = 0; i < 256; i++) lastSeen[i] = -1;
int left = 0, maxLen = 0;
for (int right = 0; s[right] != '\0'; right++) {
unsigned char c = (unsigned char)s[right];
if (lastSeen[c] >= left) {
left = lastSeen[c] + 1;
}
lastSeen[c] = right;
int len = right - left + 1;
if (len > maxLen) maxLen = len;
}
return maxLen;
}
int main(void) {
printf("%d\n", longestUniqueSubstr("abcabcbb"));
printf("%d\n", longestUniqueSubstr("bbbbb"));
printf("%d\n", longestUniqueSubstr("pwwkew"));
return 0;
}
Expected output:
3 1 3
Time: O(n), Space: O(1) (fixed 256-int array)
Sliding Window Problems in C
This program implements and demonstrates both fixed-size and variable-size sliding window patterns across several classic problems.
/**
* sliding_window.c
* Demonstrates fixed-size and variable-size sliding window patterns.
* Problems covered:
* 1. Maximum sum of subarray of size k (fixed)
* 2. Minimum sum of subarray of size k (fixed)
* 3. Longest substring without repeating characters (variable)
* 4. Smallest subarray with sum >= target (variable)
* 5. Maximum average of any subarray of size k (fixed, floating-point)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <limits.h>
#define MAX_LINE_LEN 100
/* ============================================================
* Fixed-size sliding window: maximum sum of size k
* ============================================================ */
long long maxSumFixedK(const int arr[], int n, int k) {
if (k <= 0 || n < k) return LLONG_MIN;
long long windowSum = 0;
for (int i = 0; i < k; i++) windowSum += arr[i];
long long maxSum = windowSum;
for (int i = k; i < n; i++) {
windowSum += arr[i] - arr[i - k];
if (windowSum > maxSum) maxSum = windowSum;
}
return maxSum;
}
/* ============================================================
* Fixed-size sliding window: minimum sum of size k
* ============================================================ */
long long minSumFixedK(const int arr[], int n, int k) {
if (k <= 0 || n < k) return LLONG_MAX;
long long windowSum = 0;
for (int i = 0; i < k; i++) windowSum += arr[i];
long long minSum = windowSum;
for (int i = k; i < n; i++) {
windowSum += arr[i] - arr[i - k];
if (windowSum < minSum) minSum = windowSum;
}
return minSum;
}
/* ============================================================
* Variable-size sliding window:
* Longest substring without repeating characters
* ============================================================ */
int longestUniqueSubstr(const char *s) {
int lastSeen[256];
for (int i = 0; i < 256; i++) lastSeen[i] = -1;
int left = 0, maxLen = 0;
for (int right = 0; s[right] != '\0'; right++) {
unsigned char c = (unsigned char)s[right];
if (lastSeen[c] >= left) {
left = lastSeen[c] + 1;
}
lastSeen[c] = right;
int len = right - left + 1;
if (len > maxLen) maxLen = len;
}
return maxLen;
}
/* ============================================================
* Variable-size sliding window:
* Smallest subarray with sum >= target (positive integers)
* Returns the length or 0 if none exists.
* ============================================================ */
int smallestSubarraySumGE(const int arr[], int n, long long target) {
if (n <= 0 || target <= 0) return 0;
long long windowSum = 0;
int left = 0;
int minLen = n + 1;
for (int right = 0; right < n; right++) {
windowSum += arr[right];
/* Shrink while condition still holds */
while (windowSum >= target) {
int len = right - left + 1;
if (len < minLen) minLen = len;
windowSum -= arr[left];
left++;
}
}
return (minLen == n + 1) ? 0 : minLen;
}
/* ============================================================
* Fixed-size sliding window: maximum average of size k
* ============================================================ */
double maxAverageFixedK(const int arr[], int n, int k) {
if (k <= 0 || n < k) return 0.0;
long long windowSum = 0;
for (int i = 0; i < k; i++) windowSum += arr[i];
long long maxSum = windowSum;
for (int i = k; i < n; i++) {
windowSum += arr[i] - arr[i - k];
if (windowSum > maxSum) maxSum = windowSum;
}
return (double)maxSum / k;
}
/* ============================================================
* Utility
* ============================================================ */
void printArray(const int arr[], int n) {
printf("[");
for (int i = 0; i < n; i++) {
printf("%d", arr[i]);
if (i < n - 1) printf(", ");
}
printf("]");
}
static void demoMaxSumFixed(void) {
printf("\n=== Max Sum of Subarray of Size k ===\n");
int a1[] = {5, 2, -1, 0, 3};
int n1 = 5, k1 = 3;
printf("arr = "); printArray(a1, n1);
printf(", k = %d → %lld\n", k1, maxSumFixedK(a1, n1, k1));
int a2[] = {1, 4, 2, 10, 23, 3, 1, 0, 20};
int n2 = 9, k2 = 4;
printf("arr = "); printArray(a2, n2);
printf(", k = %d → %lld\n", k2, maxSumFixedK(a2, n2, k2));
int a3[] = {-5, -2, -8, -1};
int n3 = 4, k3 = 2;
printf("arr = "); printArray(a3, n3);
printf(", k = %d → %lld (all negative)\n", k3, maxSumFixedK(a3, n3, k3));
}
static void demoMinSumFixed(void) {
printf("\n=== Min Sum of Subarray of Size k ===\n");
int a1[] = {5, 2, -1, 0, 3};
int n1 = 5, k1 = 3;
printf("arr = "); printArray(a1, n1);
printf(", k = %d → %lld\n", k1, minSumFixedK(a1, n1, k1));
int a2[] = {10, 4, 2, 5, 6, 3, 8, 1};
int n2 = 8, k2 = 3;
printf("arr = "); printArray(a2, n2);
printf(", k = %d → %lld\n", k2, minSumFixedK(a2, n2, k2));
}
static void demoLongestUnique(void) {
printf("\n=== Longest Substring Without Repeating Chars ===\n");
const char *tests[] = {"abcabcbb", "bbbbb", "pwwkew", "", "abcdef"};
for (int i = 0; i < 5; i++) {
printf(" \"%s\" → %d\n", tests[i], longestUniqueSubstr(tests[i]));
}
}
static void demoSmallestSubarray(void) {
printf("\n=== Smallest Subarray with Sum >= Target ===\n");
int a1[] = {2, 3, 1, 2, 4, 3};
int n1 = 6;
long long target1 = 7;
printf("arr = "); printArray(a1, n1);
printf(", target = %lld → length %d\n", target1, smallestSubarraySumGE(a1, n1, target1));
int a2[] = {1, 4, 4};
int n2 = 3;
long long target2 = 4;
printf("arr = "); printArray(a2, n2);
printf(", target = %lld → length %d\n", target2, smallestSubarraySumGE(a2, n2, target2));
int a3[] = {1, 1, 1, 1, 1, 1, 1, 1};
int n3 = 8;
long long target3 = 11;
printf("arr = "); printArray(a3, n3);
printf(", target = %lld → length %d (none)\n", target3, smallestSubarraySumGE(a3, n3, target3));
}
static void demoMaxAverage(void) {
printf("\n=== Maximum Average of Subarray of Size k ===\n");
int a1[] = {1, 12, -5, -6, 50, 3};
int n1 = 6, k1 = 4;
printf("arr = "); printArray(a1, n1);
printf(", k = %d → %.5f\n", k1, maxAverageFixedK(a1, n1, k1));
}
static void demoEdgeCases(void) {
printf("\n=== Edge Cases ===\n");
/* k > n */
int a1[] = {1, 2, 3};
printf("k > n: maxSumFixedK = %lld\n", maxSumFixedK(a1, 3, 5));
/* k = 0 */
printf("k = 0: maxSumFixedK = %lld\n", maxSumFixedK(a1, 3, 0));
/* k = n */
printf("k = n: maxSumFixedK = %lld\n", maxSumFixedK(a1, 3, 3));
/* k = 1 */
printf("k = 1: maxSumFixedK = %lld\n", maxSumFixedK(a1, 3, 1));
/* Empty string */
printf("Empty string: %d\n", longestUniqueSubstr(""));
/* Target too large */
int a2[] = {1, 2};
printf("Target unreachable: %d\n", smallestSubarraySumGE(a2, 2, 100));
/* Target 0 */
printf("Target 0: %d\n", smallestSubarraySumGE(a2, 2, 0));
}
int main(void) {
int choice;
char buffer[MAX_LINE_LEN];
printf("=== Sliding Window Technique Demo ===\n");
while (1) {
printf("\n--- Menu ---\n");
printf("1. Max Sum Fixed Size (k)\n");
printf("2. Min Sum Fixed Size (k)\n");
printf("3. Longest Substring Without Repeats\n");
printf("4. Smallest Subarray with Sum >= Target\n");
printf("5. Maximum Average of Size k\n");
printf("6. Edge Cases\n");
printf("7. Exit\n");
printf("Enter choice: ");
fflush(stdout);
if (fgets(buffer, sizeof(buffer), stdin) == NULL) {
fprintf(stderr, "Error reading choice.\n");
return EXIT_FAILURE;
}
choice = atoi(buffer);
switch (choice) {
case 1: demoMaxSumFixed(); break;
case 2: demoMinSumFixed(); break;
case 3: demoLongestUnique(); break;
case 4: demoSmallestSubarray(); break;
case 5: demoMaxAverage(); break;
case 6: demoEdgeCases(); break;
case 7:
printf("Exiting.\n");
return EXIT_SUCCESS;
default:
printf("Invalid choice.\n");
break;
}
}
return EXIT_SUCCESS;
}
Explanation of Each Problem
- Max Sum Fixed Size: Maintains a running window sum; updates by subtracting the outgoing element and adding the incoming one.
- Min Sum Fixed Size: Same as above but tracks the minimum instead.
- Longest Unique Substring: Uses
lastSeen[256]to know when a duplicate is inside the window; shrinksleftpast the previous occurrence. - Smallest Subarray with Sum ≥ Target: Expands
right; shrinksleftwhile the condition holds. Tracks the minimum length. - Max Average of Size k: Same as max sum, divided by
k.
Expected Output (sample run)
=== Max Sum of Subarray of Size k === arr = [5, 2, -1, 0, 3], k = 3 → 6 arr = [1, 4, 2, 10, 23, 3, 1, 0, 20], k = 4 → 39 arr = [-5, -2, -8, -1], k = 2 → -3 (all negative) === Min Sum of Subarray of Size k === arr = [5, 2, -1, 0, 3], k = 3 → 1 arr = [10, 4, 2, 5, 6, 3, 8, 1], k = 3 → 9 === Longest Substring Without Repeating Chars === "abcabcbb" → 3 "bbbbb" → 1 "pwwkew" → 3 "" → 0 "abcdef" → 6 === Smallest Subarray with Sum >= Target === arr = [2, 3, 1, 2, 4, 3], target = 7 → length 2 arr = [1, 4, 4], target = 4 → length 1 arr = [1, 1, 1, 1, 1, 1, 1, 1], target = 11 → length 0 (none) === Maximum Average of Subarray of Size k === arr = [1, 12, -5, -6, 50, 3], k = 4 → 12.75000 === Edge Cases === k > n: maxSumFixedK = -9223372036854775808 k = 0: maxSumFixedK = -9223372036854775808 k = n: maxSumFixedK = 6 k = 1: maxSumFixedK = 3 Empty string: 0 Target unreachable: 0 Target 0: 0
Shrinking and Boundary Mistakes
1. Off-by-One in Window Bounds
The window of size k starting at i spans [i, i + k - 1]. Sliding to i + 1 adds arr[i + k] and removes arr[i].
windowSum += arr[i] - arr[i - k]; /* Correct for i ≥ k */
2. k > n or k <= 0
Return a sentinel (or error). Do not silently produce garbage.
if (k <= 0 || n < k) return LLONG_MIN;
3. Integer Overflow
Sums can grow beyond int.
Solution: Use long long for the window sum and result.
4. Variable Window: left > right
If left jumps past right (e.g., duplicate handling), reset it.
left = lastSeen[c] + 1;
5. Variable Window with Negative Numbers
The “smallest subarray with sum ≥ target” approach assumes positive numbers. With negatives, the sliding window invariant breaks — use prefix sums + deque instead.
6. Sliding Window is Not Always Applicable
Requires a monotone invariant: when a window violates a condition, shrinking must restore it.
7. Mutating Inputs
All sliding window approaches leave the input untouched.
8. Fixed-Size Initialization
Compute the initial window sum correctly (first k elements).
9. Floating-Point Averages
Dividing a long long by k gives better precision than accumulating floats directly.
10. Memory Considerations
- Fixed window: O(1) extra space.
- Variable window: O(1) to O(alphabet) space.
- Use
long longfor sums. - No heap allocation needed in typical cases.
Sliding Window Summary
The Sliding Window Technique is a fundamental pattern for subarray and substring problems. It reduces O(n²) to O(n) by reusing computation across adjacent windows.
Key Takeaways
- Two variants: fixed size and variable size.
- Fixed:
window_sum += arr[i] - arr[i - k]. - Variable: expand
right, shrinkleftas needed. - Use
long longfor sums to prevent overflow. - Requires positive numbers for sum-based variants.
- Applicable to arrays, strings, and streams.
Best Practices
- Identify the window type (fixed vs. variable) before coding.
- Initialize the first window explicitly.
- Slide by subtracting outgoing and adding incoming.
- Track optimum (max/min/longest/shortest) during the slide.
- Use
long longfor sums. - Handle
k <= 0,k > n, empty inputs. - Ensure the invariant is monotone — sliding windows don’t work for arbitrary conditions.
- Prefer fixed-size sliding over nested loops for
k-sized queries. - Test with negatives, zeros, duplicates, and boundary sizes.
- Profile against naive solutions to verify correctness.
By mastering sliding windows, you’ll solve a large family of subarray and substring problems with elegant linear-time algorithms.
