Sliding Window on Arrays in DSA C++ - Time & Space Complexity
We want to understand how fast the sliding window technique works on arrays.
Specifically, how the number of steps changes as the array gets bigger.
Analyze the time complexity of the following code snippet.
int maxSumSubarray(const vector<int>& arr, int k) {
int maxSum = 0, windowSum = 0;
int windowStart = 0;
for (int windowEnd = 0; windowEnd < arr.size(); windowEnd++) {
windowSum += arr[windowEnd];
if (windowEnd >= k - 1) {
maxSum = max(maxSum, windowSum);
windowSum -= arr[windowStart];
windowStart++;
}
}
return maxSum;
}
This code finds the maximum sum of any subarray of size k using a sliding window.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single for-loop that moves the window end across the array.
- How many times: The loop runs once for each element in the array, so n times.
- The window start pointer moves forward only when the window size reaches k, also at most n times.
As the array size grows, the loop runs more times, but each element is added and removed from the window once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions and up to 10 subtractions |
| 100 | About 100 additions and up to 100 subtractions |
| 1000 | About 1000 additions and up to 1000 subtractions |
Pattern observation: The operations grow linearly with the input size.
Time Complexity: O(n)
This means the time taken grows directly in proportion to the size of the array.
[X] Wrong: "The nested if inside the loop makes this O(n²) because it looks like two loops."
[OK] Correct: The inner if only runs once per iteration and the window start pointer moves forward at most n times, so the total work is still linear.
Understanding sliding window time complexity helps you explain efficient solutions for many array problems in interviews.
"What if we changed the window size k to vary with input size n, like k = n/2? How would the time complexity change?"
Practice
Solution
Step 1: Understand the sliding window concept
The sliding window technique moves a fixed-size window over the array to process subarrays efficiently.Step 2: Identify the purpose
It avoids recomputing sums or other values for each subarray by updating results incrementally.Final Answer:
To efficiently process subarrays of fixed size without recomputing everything -> Option CQuick Check:
Sliding window = efficient fixed-size subarray processing [OK]
- Confusing sliding window with sorting
- Thinking it reverses arrays
- Assuming it finds max of whole array only
k over an array arr of length n in C++?Solution
Step 1: Determine valid window start indices
The window of size k can start at indices from 0 up to n-k to fit inside the array.Step 2: Check loop condition
The loop must run while i <= n-k to include the last valid window.Final Answer:
for (int i = 0; i <= n - k; i++) -> Option DQuick Check:
Loop runs from 0 to n-k inclusive [OK]
- Using i < n instead of i <= n-k
- Incrementing i by k skips windows
- Starting loop at k instead of 0
int arr[] = {1, 3, 2, 6, -1, 4, 1, 8, 2};
int n = 9, k = 5;
int max_sum = 0, window_sum = 0;
for (int i = 0; i < k; i++) {
window_sum += arr[i];
}
max_sum = window_sum;
for (int i = k; i < n; i++) {
window_sum += arr[i] - arr[i - k];
if (window_sum > max_sum) max_sum = window_sum;
}
std::cout << max_sum << std::endl;Solution
Step 1: Calculate initial window sum of first 5 elements
Sum = 1+3+2+6+(-1) = 11Step 2: Slide window and update sums
Next windows:
i=5: sum=11+4-1=14
i=6: sum=14+1-3=12
i=7: sum=12+8-2=18
i=8: sum=18+2-6=14
Max sum found is 18Final Answer:
18 -> Option AQuick Check:
Max sliding window sum = 18 [OK]
- Not subtracting the element leaving the window
- Incorrect initial sum calculation
- Off-by-one errors in loop limits
k:int min_sum = INT_MAX, window_sum = 0;
for (int i = 0; i < n; i++) {
window_sum += arr[i];
if (i >= k) {
window_sum -= arr[i - k - 1];
}
if (i >= k - 1 && window_sum < min_sum) {
min_sum = window_sum;
}
}Solution
Step 1: Check subtraction timing
The conditionif (i >= k)for subtraction is correct; it starts after the first full window of size k.Step 2: Identify the index bug
The code subtractsarr[i - k - 1], but it should bearr[i - k]. This is off-by-one; fori = k, it subtractsarr[-1]instead ofarr[0].Final Answer:
The subtraction should happen when i >= k, but the subtraction index is off by one -> Option AQuick Check:
Indexi - k - 1causes arr[-1] access [OK]
- Starting subtraction too early or too late
- Using wrong index for subtraction
- Not updating min_sum correctly
arr and an integer k, how would you find the maximum average of any subarray of size k using the sliding window technique?Solution
Step 1: Use sliding window to find max sum of size k
Sliding window efficiently finds max sum by adding new element and removing old one.Step 2: Calculate max average from max sum
Divide the max sum by k to get the maximum average.Final Answer:
Use sliding window to find max sum of subarrays of size k, then divide max sum by k -> Option BQuick Check:
Max average = max sum / k using sliding window [OK]
- Sorting array instead of using sliding window
- Using nested loops causing inefficiency
- Dividing sums incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
