Hint: Sum slices of size window_size in a loop [OK]
Common Mistakes:
Incorrect loop range causing index errors
Summing wrong slices
Confusing window size with list length
4. The following code tries to implement a sliding window sum but has a bug. What is the error?
data = [2, 4, 6, 8]
window_size = 2
result = []
for i in range(len(data) - window_size):
window_sum = sum(data[i:i+window_size])
result.append(window_sum)
print(result)
medium
A. The result list is not initialized.
B. The sum function is used incorrectly.
C. The loop range misses the last window, causing incomplete results.
D. Window size is larger than data length.
Solution
Step 1: Analyze the loop range
The loop runs from 0 to len(data) - window_size - 1, which is 4 - 2 - 1 = 1, so only indices 0 and 1.
Step 2: Identify missing last window
The last valid window starts at index 2 (data[2:4]), but the loop excludes it because it should run to len(data) - window_size + 1.
Final Answer:
The loop range misses the last window, causing incomplete results. -> Option C
Quick Check:
Loop range must cover all windows [OK]
Hint: Use range(len(data) - window_size + 1) for full coverage [OK]
Common Mistakes:
Using wrong loop range causing missed windows
Misusing sum function
Not initializing result list
5. You want to find the maximum sum of any sliding window of size 4 in a large list data. Which approach is most efficient?
hard
A. Use a sliding window by adding the new element and subtracting the oldest element from the previous sum.
B. Calculate sum of each window from scratch using sum(data[i:i+4]) in a loop.
C. Sort the entire list and pick the top 4 elements to sum.
D. Use recursion to calculate sums of all windows.
Solution
Step 1: Understand the problem of efficiency
Calculating sum from scratch for each window is slow for large data because it repeats work.
Step 2: Apply sliding window optimization
By keeping the previous window sum, add the new element and subtract the oldest element to get the next sum quickly.
Step 3: Evaluate other options
Sorting does not help find consecutive window sums; recursion adds overhead and is inefficient here.
Final Answer:
Use a sliding window by adding the new element and subtracting the oldest element from the previous sum. -> Option A
Quick Check:
Sliding window sum update = add new - remove old [OK]
Hint: Update sums by adding new and removing old element [OK]