Sliding Window on Arrays in DSA Rust - Time & Space Complexity
We want to understand how fast the sliding window technique runs on arrays.
Specifically, how the number of steps grows as the array gets bigger.
Analyze the time complexity of the following code snippet.
fn max_sum_subarray(arr: &[i32], k: usize) -> i32 {
let mut max_sum = i32::MIN;
let mut window_sum = 0;
for i in 0..k {
window_sum += arr[i];
}
max_sum = window_sum;
for i in k..arr.len() {
window_sum += arr[i] - arr[i - k];
if window_sum > max_sum {
max_sum = window_sum;
}
}
max_sum
}
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: Looping through the array twice: once to sum the first window, once to slide the window.
- How many times: The first loop runs k times, the second loop runs (n - k) times, where n is the 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 number of steps grows directly with the size of the array.
Time Complexity: O(n)
This means the time to run grows in a straight line as the array gets bigger.
[X] Wrong: "Sliding window runs in O(n*k) because it looks at k elements each time it moves."
[OK] Correct: The window sum updates by adding one new element and removing one old element, so it does not sum all k elements each time.
Knowing sliding window time complexity helps you explain efficient solutions clearly and confidently.
"What if we changed the window size k to vary with n, like 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 recomputing sums or other values for each subarray by updating results incrementally.Final Answer:
To efficiently process subarrays of fixed size without recomputing everything -> Option BQuick 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 only
nums?Solution
Step 1: Determine valid loop range for window size 3
Window covers indices i, i+1, i+2, so i+3 must be ⤠nums.len(). Thus, i < nums.len() - 2.Step 2: Check each option's range
for i in 0..nums.len() - 2 { let window = &nums[i..i+3]; } uses 0..nums.len()-2, which is correct. Others are off by one or more.Final Answer:
for i in 0..nums.len() - 2 { let window = &nums[i..i+3]; } -> Option AQuick Check:
Loop till len-2 for size 3 window [OK]
- Using len()-3 which is too small
- Looping till len() causing out-of-bounds
- Incorrect slice ranges causing panic
let nums = vec![1, 3, 5, 7, 9];
let k = 3;
let mut sums = Vec::new();
for i in 0..nums.len() - k + 1 {
let window_sum: i32 = nums[i..i+k].iter().sum();
sums.push(window_sum);
}
println!("{:?}", sums);Solution
Step 1: Identify windows and sums
Windows of size 3 are: [1,3,5], [3,5,7], [5,7,9]. Their sums are 9, 15, 21 respectively.Step 2: Confirm output vector
The sums vector collects these sums and prints them as [9, 15, 21].Final Answer:
[9, 15, 21] -> Option CQuick Check:
Sum windows = [9, 15, 21] [OK]
- Summing wrong slices
- Off-by-one in loop range
- Confusing sums with elements
let nums = vec![4, 2, 1, 7];
let k = 2;
let mut max_sum = 0;
for i in 0..nums.len() - k {
let sum: i32 = nums[i..i+k].iter().sum();
if sum > max_sum {
max_sum = sum;
}
}
println!("{}", max_sum);Solution
Step 1: Check loop range for window size 2
Windows are nums[i..i+2], so i must go up to nums.len() - 2 inclusive, meaning 0..nums.len()-1 or 0..nums.len()-k+1.Step 2: Identify off-by-one error
Current loop ends at nums.len()-k exclusive, missing last window. Correct range is 0..nums.len()-k+1.Final Answer:
Loop range should be 0..nums.len() - k + 1 to include last window -> Option DQuick Check:
Loop till len-k+1 for full windows [OK]
- Using wrong loop range causing missed windows
- Initializing max_sum to 0 causing wrong max if negatives
- Unnecessary changes to sum calculation
nums and window size k, how can you find the maximum sum of any subarray of size k using sliding window in Rust efficiently?Solution
Step 1: Compute initial window sum
Sum the first k elements to get the starting window sum.Step 2: Slide window and update sums
For each next position, add the new element and subtract the element leaving the window, updating max sum if needed.Step 3: Avoid recomputing sums fully
This approach avoids nested loops and is efficient with O(n) time complexity.Final Answer:
Calculate sum of first k elements, then slide window by adding next element and subtracting first element of previous window, updating max sum each time -> Option AQuick Check:
Sliding window sum update = efficient max sum [OK]
- Using nested loops causing slow O(n²) time
- Sorting array which changes element order
- Reversing array which doesn't help sum
Ready to prove it?
Pass the test and this pattern moves unknown
