Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to slide the window by moving the start index forward.
DSA Javascript
let start = 0; let end = 3; while (end < arr.length) { // process window arr[start..end] start = start [1] 1; end++; }
Attempts:
3 left
š” Hint
Common Mistakes
Using '-' will move the window backward, causing errors.
ā Incorrect
To move the window forward, we increase the start index by 1 using '+'.
2fill in blank
mediumComplete the code to calculate the sum of the current sliding window.
DSA Javascript
let windowSum = 0; for (let i = start; i [1] end; i++) { windowSum += arr[i]; }
Attempts:
3 left
š” Hint
Common Mistakes
Using '<' excludes the last element of the window.
ā Incorrect
The loop should include the end index, so use '<=' to cover all elements in the window.
3fill in blank
hardFix the error in updating the window sum when sliding the window forward by one element.
DSA Javascript
windowSum = windowSum - arr[start] [1] arr[end + 1];
Attempts:
3 left
š” Hint
Common Mistakes
Using '-' will subtract the new element, causing incorrect sums.
ā Incorrect
When sliding the window, subtract the element leaving and add the new element entering the window using '+'.
4fill in blank
hardFill both blanks to create a sliding window that finds the maximum sum of any window of size k.
DSA Javascript
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 = windowSum [1] arr[i - k] [2] arr[i]; if (windowSum > maxSum) { maxSum = windowSum; } }
Attempts:
3 left
š” Hint
Common Mistakes
Using '+' for both will add too much.
Using '-' for both will subtract too much.
ā Incorrect
To slide the window, subtract the element leaving (arr[i - k]) and add the new element entering (arr[i]).
5fill in blank
hardFill all three blanks to create a sliding window that finds the minimum length subarray with sum at least target.
DSA Javascript
let minLength = Infinity; let start = 0; let currentSum = 0; for (let end = 0; end < arr.length; end++) { currentSum += arr[end]; while (currentSum [1] target) { minLength = Math.min(minLength, end [2] start [3] 1); currentSum -= arr[start]; start++; } }
Attempts:
3 left
š” Hint
Common Mistakes
Using '<=' instead of '>=' in the while condition.
Calculating length incorrectly.
ā Incorrect
The loop shrinks the window while currentSum is greater or equal to target. The length is end - start + 1.
