Data Structures & Algorithms Sliding Window
💡
Exercise 41

Sliding Window Technique 10 XP Easy

Ctrl+Enter Run Ctrl+S Save

The Sliding Window technique is one of the most powerful array/string patterns! 🪟

💡 Think of it like this: Imagine looking at a city through a window on a moving train. The window shows a portion of the city, and as the train moves, the view shifts. In coding, our "window" is a range of elements in an array, and we slide it along!

💭 Go for it! Apply the approach above in your own code. If you get stuck, use the hint below! 🔥

Two types of sliding windows:

  • 📏 Fixed-size: Window always has exactly k elements. Slide by adding right, removing left.
  • ↔️ Variable-size: Window grows/shrinks based on a condition. Use two pointers (left, right).
  • 🔑 Key insight: We're reusing work from the previous window instead of starting over!
  • ⚡ Turns O(n × k) brute force into O(n) — a huge speedup for large inputs.

Variable-size window template:

def variable_window(arr): left = 0 for right in range(len(arr)): # Expand window: add arr[right] while window_is_invalid(): # Shrink window: remove arr[left] left += 1 # Update answer with current valid window
📋 Instructions
Implement `max_sum_subarray(nums, k)` that finds the maximum sum of any `k` consecutive elements. Test with `nums = [2, 1, 5, 1, 3, 2]` and `k = 3`. Print the result.
Calculate sum of first k elements. Then slide: add nums[i], subtract nums[i-k]. Track the maximum sum.
⚠️ Try solving it yourself first — you'll learn more!
# Fixed-size window: Find max sum of k consecutive elements
def max_sum_k(arr, k):
    window_sum = sum(arr[:k])    # First window
    max_sum = window_sum
    
    for i in range(k, len(arr)):
        window_sum += arr[i]      # Add new element (right side)
        window_sum -= arr[i - k]  # Remove old element (left side)
        max_sum = max(max_sum, window_sum)
    
    return max_sum
# Instead of recalculating sum for every window (O(n×k)),
# we just add one and remove one (O(n))!
🧪 Test Cases
Input
max_sum_subarray([2, 1, 5, 1, 3, 2], 3)
Expected
9
Test case 1
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.