0
0
DSA Pythonprogramming

Sliding Window on Arrays in DSA Python

Choose your learning style9 modes available
Mental Model
A sliding window moves over the array to look at a small part at a time, updating the result 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] [6] [7]
Window: ↑ -> -> (covers first 3 elements)
Dry Run Walkthrough
Input: array: [1, 3, 2, 5, 7, 2, 4], window size: 3
Goal: Find the maximum sum of any 3 consecutive elements
Step 1: Calculate sum of first window (first 3 elements)
Window covers [1, 3, 2], sum = 6
Why: We need a starting sum to compare with next windows
Step 2: Slide window right by 1: remove 1, add 5
Window covers [3, 2, 5], sum = 10
Why: Update sum efficiently without adding all elements again
Step 3: Slide window right by 1: remove 3, add 7
Window covers [2, 5, 7], sum = 14
Why: Keep updating sum to find max without full recalculation
Step 4: Slide window right by 1: remove 2, add 2
Window covers [5, 7, 2], sum = 14
Why: Check if new sum is max or equal max
Step 5: Slide window right by 1: remove 5, add 4
Window covers [7, 2, 4], sum = 13
Why: Final window sum to compare
Result:
Maximum sum is 14 from windows [2, 5, 7] and [5, 7, 2]
Annotated Code
DSA Python
class SlidingWindow:
    def max_sum_subarray(self, arr, k):
        if len(arr) < k or k == 0:
            return 0
        window_sum = sum(arr[:k])  # sum of first window
        max_sum = window_sum
        for i in range(k, len(arr)):
            window_sum += arr[i] - arr[i - k]  # slide window right
            if window_sum > max_sum:
                max_sum = window_sum
        return max_sum

# Driver code
arr = [1, 3, 2, 5, 7, 2, 4]
k = 3
sw = SlidingWindow()
print(sw.max_sum_subarray(arr, k))
window_sum = sum(arr[:k]) # sum of first window
Calculate initial sum of the first window
window_sum += arr[i] - arr[i - k] # slide window right
Update window sum by removing left element and adding new right element
if window_sum > max_sum: max_sum = window_sum
Keep track of maximum sum found so far
OutputSuccess
14
Complexity Analysis
Time: O(n) because we visit each element once while sliding the window
Space: O(1) because we only store sums and counters, no extra array
vs Alternative: Naive approach sums each window fully in O(k) time, leading to O(n*k) total, which is slower
Edge Cases
Empty array or window size zero
Returns 0 immediately as no valid window exists
DSA Python
if len(arr) < k or k == 0:
    return 0
Window size equals array length
Returns sum of entire array as only one window exists
DSA Python
window_sum = sum(arr[:k])  # sum of first window
Window size larger than array length
Returns 0 because no window can be formed
DSA Python
if len(arr) < k or k == 0:
    return 0
When to Use This Pattern
When you need to find something about all subarrays of fixed size, use sliding window to avoid repeated work and improve efficiency.
Common Mistakes
Mistake: Recalculating the sum of the window from scratch every time instead of updating it
Fix: Update the sum by subtracting the element leaving the window and adding the new element entering
Summary
Finds max sum of any subarray of fixed size by moving a window over the array
Use when you need to analyze all subarrays of a fixed length efficiently
The key is to update the window sum by removing the left element and adding the right element instead of recalculating