Sliding Window on Arrays in DSA C# - Time & Space Complexity
We want to understand how the time needed changes when using the sliding window technique on arrays.
Specifically, how does the number of steps grow as the array gets bigger?
Analyze the time complexity of the following code snippet.
int MaxSumSubarray(int[] arr, int k) {
int maxSum = 0, windowSum = 0;
for (int i = 0; i < k; i++) {
windowSum += arr[i];
}
maxSum = windowSum;
for (int i = k; i < arr.Length; i++) {
windowSum += arr[i] - arr[i - k];
if (windowSum > maxSum) maxSum = windowSum;
}
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: Two loops that each run over parts of the array.
- How many times: First loop runs k times, second loop runs (n - k) times, where n is array length.
As the array size grows, the total steps grow roughly in a straight line with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The work grows directly with the size of the array.
Time Complexity: O(n)
This means the time to run grows in a straight line as the array gets bigger.
[X] Wrong: "The inner loop makes this O(n*k) because it looks like nested loops."
[OK] Correct: The loops are separate, not nested, so total steps add up, not multiply.
Understanding sliding window time complexity helps you explain efficient solutions clearly and confidently.
"What if we changed the window size k to vary with n, like k = n/2? How would the time complexity change?"
Practice
sliding window technique when working with arrays?Solution
Step 1: Understand the sliding window concept
The sliding window technique moves a fixed-size window over the array to calculate values like sums or averages efficiently.Step 2: Identify the purpose
It avoids recalculating the sum or property for each new window by updating the previous result, making it efficient.Final Answer:
To efficiently find subarray sums or properties without recalculating everything each time -> Option AQuick Check:
Sliding window = efficient subarray calculation [OK]
- Confusing sliding window with sorting
- Thinking it reverses arrays
- Assuming it finds max element globally
k over an array arr in C#?Solution
Step 1: Determine valid window start indices
The window of size k can start at index 0 up to index arr.Length - k to avoid overflow.Step 2: Check loop condition
The loop must run while i <= arr.Length - k to include the last valid window.Final Answer:
for (int i = 0; i <= arr.Length - k; i++) -> Option BQuick Check:
Loop runs from 0 to arr.Length - k [OK]
- Using < instead of <= causing last window skip
- Starting loop at 1 instead of 0
- Looping beyond array length causing errors
int[] arr = {1, 3, 2, 6, -1, 4, 1, 8, 2};
int k = 5;
int maxSum = 0;
int windowSum = 0;
for (int i = 0; i < k; i++)
windowSum += arr[i];
maxSum = windowSum;
for (int i = k; i < arr.Length; i++) {
windowSum += arr[i] - arr[i - k];
if (windowSum > maxSum)
maxSum = windowSum;
}
Console.WriteLine(maxSum);Solution
Step 1: Calculate initial window sum of first 5 elements
Sum of arr[0..4] = 1+3+2+6+(-1) = 11Step 2: Slide window and update sums
Next windows and sums: - i=5: windowSum = 11 + 4 - 1 = 14 (maxSum=14) - i=6: windowSum = 14 + 1 - 3 = 12 (maxSum=14) - i=7: windowSum = 12 + 8 - 2 = 18 (maxSum=18) - i=8: windowSum = 18 + 2 - 6 = 14 (maxSum=18)Final Answer:
18 -> Option CQuick Check:
Max sliding window sum = 18 [OK]
- Not subtracting the element leaving the window
- Starting loop from wrong index
- Incorrect initial sum calculation
k:int maxSum = 0;
int windowSum = 0;
for (int i = 0; i < arr.Length; i++) {
windowSum += arr[i];
if (i >= k) {
windowSum -= arr[i - k];
if (windowSum > maxSum)
maxSum = windowSum;
}
}
Console.WriteLine(maxSum);Solution
Step 1: Analyze maxSum initialization
maxSum is 0 initially, which fails if all sums are negative because maxSum will never update.Step 2: Correct initialization for negative values
Initialize maxSum to int.MinValue to correctly track maximum sum even if negative.Final Answer:
maxSum should be initialized to int.MinValue to handle negative sums -> Option AQuick Check:
maxSum init = int.MinValue for negatives [OK]
- Initializing maxSum to 0 causes wrong max for negative arrays
- Changing loop start incorrectly
- Resetting windowSum inside loop breaks sliding window
S. Which of the following describes the correct approach?Solution
Step 1: Use two pointers to represent window boundaries
Start both pointers at the beginning and expand the right pointer to include elements while sum ≤ S.Step 2: Shrink window from left when sum exceeds S
If sum > S, move left pointer forward subtracting elements until sum ≤ S again, tracking max length.Final Answer:
Use two pointers to expand and shrink the window, updating sum and max length accordingly -> Option DQuick Check:
Two-pointer sliding window for variable length subarray [OK]
- Sorting array breaks original order needed
- Checking all subarrays is inefficient
- Using stack is not suitable for sum constraints
Ready to prove it?
Pass the test and this pattern moves unknown
