Sliding Window on Arrays in DSA Javascript - Time & Space Complexity
We want to understand how fast the sliding window technique works when processing arrays.
Specifically, how the number of steps grows as the array gets bigger.
Analyze the time complexity of the following code snippet.
function maxSumSubarray(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;
}
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 input size, not faster or slower.
Time Complexity: O(n)
This means the time to run grows in a straight line as the array gets bigger.
[X] Wrong: "The nested loop inside the sliding window makes this O(n²)."
[OK] Correct: The code only uses two separate loops, not nested loops, so it does not multiply steps but adds them, keeping it linear.
Knowing how sliding window runs efficiently helps you solve many array problems quickly and confidently in interviews.
"What if we changed the window size k to be equal to the array length n? How would the time complexity change?"
Practice
sliding window technique when working with arrays?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: Compare with other options
Sorting, reversing, or finding max in the entire array are different operations not related to sliding window.Final Answer:
To efficiently process subarrays of fixed size without recomputing everything -> Option DQuick Check:
Sliding window = efficient fixed-size subarray processing [OK]
- Confusing sliding window with sorting or reversing
- Thinking it processes the whole array at once
- Assuming it finds max without window size
k elements in JavaScript?Solution
Step 1: Understand how to get first k elements
Usingarr.slice(0, k)extracts the first k elements without modifying the array.Step 2: Sum the elements correctly
Usingreduce((a, b) => a + b, 0)sums all elements in the sliced array.Final Answer:
let sum = arr.slice(0, k).reduce((a, b) => a + b, 0); -> Option AQuick Check:
slice(0,k) + reduce sum = correct initialization [OK]
- Using reduce on whole array instead of first k elements
- Using splice which modifies the original array
- Slicing from k to end instead of 0 to k
const arr = [1, 3, 2, 6, -1, 4, 1, 8, 2];
const k = 5;
let maxSum = 0;
let windowSum = 0;
// Initialize first window sum
for(let i = 0; i < k; i++) {
windowSum += arr[i];
}
maxSum = windowSum;
// Slide the window
for(let i = k; i < arr.length; i++) {
windowSum += arr[i] - arr[i - k];
if(windowSum > maxSum) maxSum = windowSum;
}
console.log(maxSum);Solution
Step 1: Calculate initial window sum for first 5 elements
Sum of [1,3,2,6,-1] = 1+3+2+6-1 = 11Step 2: Slide window and update sums
Next windows and sums:
Remove 1, add 4: 11 - 1 + 4 = 14
Remove 3, add 1: 14 - 3 + 1 = 12
Remove 2, add 8: 12 - 2 + 8 = 18 (maxSum updated to 18)
Remove 6, add 2: 18 - 6 + 2 = 14Step 3: Find maxSum
Max sum found is 18Final Answer:
18 -> Option AQuick Check:
Max sliding window sum = 18 [OK]
- Not updating maxSum correctly
- Adding instead of subtracting old element
- Wrong initial sum calculation
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;
}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 BQuick Check:
Loop range for first window = i < k [OK]
- Using <= k causes out-of-bounds error
- Ignoring array length checks
- Incorrect initialization of maxSum
k, how would you find the length of the longest subarray with sum less than or equal to k using the sliding window technique?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 CQuick 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]
- 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
Ready to prove it?
Pass the test and this pattern moves unknown
