Sliding Window on Arrays in DSA Typescript - 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.
function maxSumSubarray(arr: number[], k: number): number {
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;
}
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 steps increase directly with the size of the array.
Time Complexity: O(n)
This means the time needed grows in a straight line as the array gets bigger.
[X] Wrong: "Sliding window always means nested loops, so it must be O(n²)."
[OK] Correct: Here, the window moves forward by one step each time without restarting, so the total work is just one pass through the array, not repeated loops inside loops.
Understanding sliding window time complexity helps you explain efficient solutions clearly and confidently in interviews.
"What if the window size k changes with input size n, for example k = n/2? How would the time complexity change?"
Practice
Solution
Step 1: Understand the sliding window concept
The sliding window technique moves a fixed-size window over the array to process subarrays efficiently.Step 2: Identify the purpose
It avoids recalculating values for overlapping parts of subarrays, improving performance.Final Answer:
To efficiently process subarrays of fixed size without repeated work -> Option DQuick Check:
Sliding window = efficient fixed-size subarray processing [OK]
- Confusing sliding window with sorting
- Thinking it reverses the array
- Assuming it finds max of whole array
arr with window size k?Solution
Step 1: Determine loop range for sliding window
The window of size k must fit inside the array, so the last start index is arr.length - k.Step 2: Check loop syntax correctness
Loop from i = 0 up to and including arr.length - k ensures all windows are covered.Final Answer:
for (let i = 0; i <= arr.length - k; i++) -> Option CQuick Check:
Loop runs from 0 to arr.length - k inclusive [OK]
- Using < instead of <= causing last window to miss
- Starting loop at 1 instead of 0
- Incrementing by k skipping windows
const arr = [1, 3, 2, 6, -1, 4, 1, 8, 2];
const k = 5;
const result: number[] = [];
let windowSum = 0;
for (let i = 0; i < k; i++) {
windowSum += arr[i];
}
result.push(windowSum);
for (let i = k; i < arr.length; i++) {
windowSum += arr[i] - arr[i - k];
result.push(windowSum);
}
console.log(result);Solution
Step 1: Calculate initial window sum for first 5 elements
1 + 3 + 2 + 6 + (-1) = 11. result = [11]Step 2: Slide window and update sums
i=5: 11 - 1 + 4 = 14
i=6: 14 - 3 + 1 = 12
i=7: 12 - 2 + 8 = 18
i=8: 18 - 6 + 2 = 14
result = [11, 14, 12, 18, 14]Final Answer:
[11, 14, 12, 18, 14] -> Option AQuick Check:
windowSum += arr[i] - arr[i - k] each slide [OK]
- Not subtracting the element leaving the window
- Incorrect initial sum calculation
- Off-by-one errors in loop indices
const arr = [2, 1, 5, 1, 3, 2];
const k = 3;
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 + arr[i] - arr[i + k];
if (windowSum > maxSum) {
maxSum = windowSum;
}
}
console.log(maxSum);Solution
Step 1: Analyze the sliding window update
The window slides by removing the element leaving the window and adding the new element entering it. The element leaving is at index i - k, not i + k.Step 2: Correct the subtraction index
Change arr[i + k] to arr[i - k] to correctly remove the leftmost element of the previous window.Final Answer:
Change arr[i + k] to arr[i - k] in the second loop -> Option BQuick Check:
Subtract element leaving window at i-k [OK]
- Using wrong index for element leaving window
- Not initializing maxSum correctly
- Loop range errors
k. Which approach below correctly implements this in TypeScript?Solution
Step 1: Understand the sliding window max sum approach
Calculate sum of first k elements as initial window sum.Step 2: Slide window across array
For each new element, add it and subtract the element leaving the window, update max sum if current sum is higher.Step 3: Avoid inefficient methods
Sorting or nested loops are less efficient; averaging does not find max sum.Final Answer:
Initialize sum of first k elements, then slide window adding new element and subtracting old, updating max sum each time -> Option AQuick Check:
Sliding window updates sum and tracks max [OK]
- Using nested loops causing slow performance
- Sorting array which changes element order
- Calculating average instead of max sum
Ready to prove it?
Pass the test and this pattern moves unknown
