Sliding Window on Arrays in DSA Python - Time & Space Complexity
We want to understand how the time taken by a sliding window approach changes as the input array grows.
Specifically, how many steps does it take to process all windows in the array?
Analyze the time complexity of the following code snippet.
def max_sum_subarray(arr, k):
max_sum = 0
window_sum = 0
for i in range(k):
window_sum += arr[i]
max_sum = window_sum
for i in range(k, len(arr)):
window_sum += arr[i] - arr[i - k]
max_sum = max(max_sum, window_sum)
return max_sum
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 traverse 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 number of operations increases directly with input size.
Time Complexity: O(n)
This means the time to complete grows linearly as the array gets bigger.
[X] Wrong: "Sliding window always takes O(k) time because the window size is k."
[OK] Correct: The window moves across the entire array, so the total work depends on n, not just k.
Understanding sliding window time complexity helps you explain efficient solutions clearly and confidently.
"What if we used nested loops instead of sliding window? How would the time complexity change?"
Practice
Solution
Step 1: Understand the sliding window purpose
The sliding window technique moves a fixed-size window over the array to process elements efficiently without recalculating everything each time.Step 2: Identify what it optimizes
It avoids repeated work on overlapping parts of the array, thus reducing time complexity compared to naive methods.Final Answer:
It reduces the time complexity by avoiding repeated calculations over overlapping subarrays. -> Option AQuick Check:
Sliding window = avoids repeated calculations [OK]
- Thinking it sorts the array
- Assuming it finds max element always
- Confusing it with reversing arrays
arr in Python?Solution
Step 1: Identify the first 3 elements slice
The first 3 elements are at indices 0, 1, and 2, so the slice is arr[0:3] because the end index is exclusive.Step 2: Use sum function on correct slice
sum(arr[0:3]) correctly sums elements at indices 0, 1, and 2.Final Answer:
window_sum = sum(arr[0:3]) -> Option AQuick Check:
sum(arr[0:3]) sums first 3 elements [OK]
- Using wrong slice indices like arr[1:4]
- Using arr[0:2] which misses the third element
- Using arr[3:6] which skips first elements
arr = [2, 1, 5, 1, 3, 2]
window_size = 3
window_sum = sum(arr[0:3])
result = [window_sum]
for i in range(3, len(arr)):
window_sum += arr[i] - arr[i - window_size]
result.append(window_sum)
print(result)Solution
Step 1: Calculate initial window sum
sum(arr[0:3]) = 2 + 1 + 5 = 8, so result starts as [8].Step 2: Slide window and update sums
i=3: window_sum = 8 + arr[3] - arr[0] = 8 + 1 - 2 = 7; result = [8,7] i=4: window_sum = 7 + arr[4] - arr[1] = 7 + 3 - 1 = 9; result = [8,7,9] i=5: window_sum = 9 + arr[5] - arr[2] = 9 + 2 - 5 = 6; result = [8,7,9,6]Final Answer:
[8, 7, 9, 6] -> Option CQuick Check:
Sliding sums = [8,7,9,6] [OK]
- Not subtracting the element leaving the window
- Incorrect initial sum calculation
- Appending wrong values to result
arr = [4, 3, 2, 1]
window_size = 2
window_sum = sum(arr[0:window_size])
result = [window_sum]
for i in range(window_size, len(arr)):
window_sum = window_sum + arr[i] + arr[i - window_size]
result.append(window_sum)
print(result)Solution
Step 1: Analyze window_sum update
The code adds both arr[i] and arr[i - window_size], but it should add the new element and subtract the element leaving the window.Step 2: Correct the update formula
Change window_sum = window_sum + arr[i] + arr[i - window_size] to window_sum = window_sum + arr[i] - arr[i - window_size].Final Answer:
The window_sum update should subtract arr[i - window_size], not add it. -> Option BQuick Check:
Subtract leaving element, not add [OK]
- Adding both new and old elements instead of subtracting old
- Wrong loop start index
- Incorrect initial sum
arr = [1, 3, 2, 6, -1, 4, 1, 8, 2] and window size 5, which sliding window sum is the maximum?Use the sliding window technique to find the maximum sum of any 5 consecutive elements.
Solution
Step 1: Calculate initial window sum for first 5 elements
sum(arr[0:5]) = 1 + 3 + 2 + 6 + (-1) = 11Step 2: Slide window and update sums, track max
i=5: sum = 11 + 4 - 1 = 14 (max=14) i=6: sum = 14 + 1 - 3 = 12 (max=14) i=7: sum = 12 + 8 - 2 = 18 (max=18) i=8: sum = 18 + 2 - 6 = 14 (max=18)Final Answer:
18 -> Option DQuick Check:
Max sliding sum = 18 [OK]
- Not updating max after each slide
- Wrong initial sum calculation
- Forgetting to subtract element leaving window
Ready to prove it?
Pass the test and this pattern moves unknown
