Hint: Update sum by subtracting left, adding right element [OK]
Common Mistakes:
Not updating maxSum correctly
Adding instead of subtracting old element
Wrong initial sum calculation
4. Identify the bug in the following sliding window code that finds the maximum sum of subarrays of size k:
function maxSlidingWindowSum(arr, k) {
let maxSum = 0;
let windowSum = 0;
for(let i = 0; i <= k; i++) {
windowSum += arr[i];
}
maxSum = windowSum;
for(let i = k; i < arr.length; i++) {
windowSum += arr[i] - arr[i - k];
if(windowSum > maxSum) maxSum = windowSum;
}
return maxSum;
}
medium
A. The subtraction in the second loop is incorrect
B. The first loop should run while i < k, not i <= k
C. maxSum should be initialized to Number.MIN_VALUE
D. The function does not handle empty arrays
Solution
Step 1: Check the first loop range
The first loop runs from i = 0 to i <= k, which means it accesses arr[k], an out-of-bound index for window size k.
Step 2: Correct the loop condition
The loop should run while i < k to sum exactly k elements starting from index 0.
Final Answer:
The first loop should run while i < k, not i <= k -> Option B
Quick Check:
Loop range for first window = i < k [OK]
Hint: Loop for first window sums exactly k elements: i < k [OK]
Common Mistakes:
Using <= k causes out-of-bounds error
Ignoring array length checks
Incorrect initialization of maxSum
5. Given an array of integers and a number k, how would you find the length of the longest subarray with sum less than or equal to k using the sliding window technique?
hard
A. Calculate prefix sums and find max subarray sum using Kadane's algorithm
B. Sort the array and use binary search to find subarrays with sum ⤠k
C. Expand the window by moving right pointer and shrink from left when sum exceeds k, track max length
D. Use nested loops to check all subarrays and pick the longest with sum ⤠k
Solution
Step 1: Use two pointers to create a sliding window
Start with both pointers at the beginning, expand right pointer to add elements to sum.
Step 2: Shrink window from left when sum exceeds k
If sum > k, move left pointer forward to reduce sum until sum ⤠k again, tracking max window length.
Step 3: Track the maximum length of valid windows
Keep updating max length whenever sum ⤠k during expansion and shrinking.
Final Answer:
Expand the window by moving right pointer and shrink from left when sum exceeds k, track max length -> Option C
Quick Check:
Sliding window with two pointers and sum check = Expand the window by moving right pointer and shrink from left when sum exceeds k, track max length [OK]
Hint: Move right to expand, left to shrink when sum > k [OK]
Common Mistakes:
Using sorting or binary search which doesn't apply here
Using nested loops causing O(n²) time
Confusing Kadane's algorithm with sum limit problem
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.