Bird
Raised Fist0
DSA Rustprogramming

Sliding Window on Arrays in DSA Rust

Choose your learning style10 modes available
Mental Model
A sliding window moves over an array to look at a small part at a time, updating as it goes.
Analogy: Imagine looking through a small window on a long fence, moving it step by step to see different parts without stepping back.
Array: [1] -> [2] -> [3] -> [4] -> [5] -> null
Window size 3:
[1] -> [2] -> [3]
↑start ↑end
Dry Run Walkthrough
Input: array: [1, 3, 2, 5, 4], window size: 3
Goal: Find the sum of each window of size 3 as it moves from start to end
Step 1: Calculate sum of first window [1, 3, 2]
[1, 3, 2, 5, 4]
Window: [1, 3, 2]
Sum = 1 + 3 + 2 = 6
Why: We need the initial sum to start sliding the window
Step 2: Slide window right by 1: remove 1, add 5
[1, 3, 2, 5, 4]
Window: [3, 2, 5]
Sum = 6 - 1 + 5 = 10
Why: Update sum efficiently by removing left and adding right element
Step 3: Slide window right by 1: remove 3, add 4
[1, 3, 2, 5, 4]
Window: [2, 5, 4]
Sum = 10 - 3 + 4 = 11
Why: Continue sliding window to cover all parts of array
Result:
Final sums: 6 -> 10 -> 11
Annotated Code
DSA Rust
fn sliding_window_sums(arr: &[i32], k: usize) -> Vec<i32> {
    let n = arr.len();
    if k > n || k == 0 {
        return vec![];
    }
    let mut sums = Vec::new();
    let mut window_sum: i32 = arr[0..k].iter().sum();
    sums.push(window_sum);
    for i in k..n {
        window_sum = window_sum - arr[i - k] + arr[i];
        sums.push(window_sum);
    }
    sums
}

fn main() {
    let arr = [1, 3, 2, 5, 4];
    let k = 3;
    let result = sliding_window_sums(&arr, k);
    for (i, sum) in result.iter().enumerate() {
        if i < result.len() - 1 {
            print!("{} -> ", sum);
        } else {
            print!("{}", sum);
        }
    }
    println!(" -> null");
}
let mut window_sum: i32 = arr[0..k].iter().sum();
Calculate initial sum of first window
for i in k..n {
Slide window from index k to end
window_sum = window_sum - arr[i - k] + arr[i];
Update sum by removing left element and adding new right element
sums.push(window_sum);
Store updated sum for current window
OutputSuccess
6 -> 10 -> 11 -> null
Complexity Analysis
Time: O(n) because we calculate the initial sum once and then update sums in constant time for each of the remaining elements
Space: O(n-k+1) because we store the sum for each sliding window position
vs Alternative: Naive approach recalculates sum for each window in O(k) time, resulting in O(n*k) total, which is slower than this O(n) method
Edge Cases
window size k is zero
Returns empty result because no window can be formed
DSA Rust
if k > n || k == 0 { return vec![]; }
window size k larger than array length
Returns empty result because window cannot fit
DSA Rust
if k > n || k == 0 { return vec![]; }
array with one element and window size 1
Returns sum equal to that single element
DSA Rust
let mut window_sum: i32 = arr[0..k].iter().sum();
When to Use This Pattern
When you need to process all subarrays or parts of fixed size in a sequence efficiently, use the sliding window pattern to avoid repeated work.
Common Mistakes
Mistake: Recalculating the sum of the window from scratch at each step
Fix: Update the sum by subtracting the element leaving the window and adding the new element entering
Mistake: Not handling cases where window size is zero or larger than array length
Fix: Add a guard clause to return empty result for invalid window sizes
Summary
Calculates values over a moving fixed-size window on an array efficiently.
Use when you want to process all subarrays of a fixed size without repeated full calculations.
The key is to update the window result by removing the old element and adding the new one as the window slides.

Practice

(1/5)
1. What is the main purpose of the sliding window technique on arrays?
easy
A. To sort the array in ascending order
B. To efficiently process subarrays of fixed size without recomputing everything
C. To reverse the array elements
D. To find the maximum element in the entire array

Solution

  1. Step 1: Understand the sliding window concept

    The sliding window technique moves a fixed-size window over the array to process subarrays efficiently.
  2. Step 2: Identify the purpose

    It avoids recomputing sums or other values for each subarray by updating results incrementally.
  3. Final Answer:

    To efficiently process subarrays of fixed size without recomputing everything -> Option B
  4. Quick Check:

    Sliding window = efficient fixed-size subarray processing [OK]
Hint: Think of a moving window that updates results quickly [OK]
Common Mistakes:
  • Confusing sliding window with sorting
  • Thinking it reverses the array
  • Assuming it finds max of whole array only
2. Which Rust code snippet correctly initializes a sliding window of size 3 over a vector nums?
easy
A. for i in 0..nums.len() - 2 { let window = &nums[i..i+3]; }
B. for i in 0..nums.len() { let window = &nums[i..i+3]; }
C. for i in 0..nums.len() - 1 { let window = &nums[i..i+3]; }
D. for i in 0..nums.len() - 3 { let window = &nums[i..i+3]; }

Solution

  1. 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.
  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.
  3. Final Answer:

    for i in 0..nums.len() - 2 { let window = &nums[i..i+3]; } -> Option A
  4. Quick Check:

    Loop till len-2 for size 3 window [OK]
Hint: Window end index = start + size; loop till len - size + 1 [OK]
Common Mistakes:
  • Using len()-3 which is too small
  • Looping till len() causing out-of-bounds
  • Incorrect slice ranges causing panic
3. What is the output of this Rust code?
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);
medium
A. [3, 5, 7]
B. [1, 3, 5]
C. [9, 15, 21]
D. [7, 9, 11]

Solution

  1. 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.
  2. Step 2: Confirm output vector

    The sums vector collects these sums and prints them as [9, 15, 21].
  3. Final Answer:

    [9, 15, 21] -> Option C
  4. Quick Check:

    Sum windows = [9, 15, 21] [OK]
Hint: Sum each 3-element slice, slide by one [OK]
Common Mistakes:
  • Summing wrong slices
  • Off-by-one in loop range
  • Confusing sums with elements
4. Find the error in this Rust code that tries to print max sum of sliding window size 2:
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);
medium
A. Window size k should be 3 instead of 2
B. max_sum should be initialized to i32::MIN instead of 0
C. Sum calculation should use fold instead of iter().sum()
D. Loop range should be 0..nums.len() - k + 1 to include last window

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    Loop range should be 0..nums.len() - k + 1 to include last window -> Option D
  4. Quick Check:

    Loop till len-k+1 for full windows [OK]
Hint: Loop till len - window size + 1 to cover all windows [OK]
Common Mistakes:
  • Using wrong loop range causing missed windows
  • Initializing max_sum to 0 causing wrong max if negatives
  • Unnecessary changes to sum calculation
5. Given an array nums and window size k, how can you find the maximum sum of any subarray of size k using sliding window in Rust efficiently?
hard
A. 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
B. Sort the array and sum the last k elements to get maximum sum
C. Use nested loops to sum every subarray of size k and track maximum sum
D. Reverse the array and sum first k elements for maximum sum

Solution

  1. Step 1: Compute initial window sum

    Sum the first k elements to get the starting window sum.
  2. 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.
  3. Step 3: Avoid recomputing sums fully

    This approach avoids nested loops and is efficient with O(n) time complexity.
  4. 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 A
  5. Quick Check:

    Sliding window sum update = efficient max sum [OK]
Hint: Add new element, subtract old to update sum fast [OK]
Common Mistakes:
  • Using nested loops causing slow O(nΒ²) time
  • Sorting array which changes element order
  • Reversing array which doesn't help sum
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard