DEV Community

Cover image for Mastering the Sliding Window Technique in Python
Rishi Shah
Rishi Shah

Posted on

Mastering the Sliding Window Technique in Python

Stop using nested loops for subarray problems.
One of the most common patterns in coding interviews is the "Subarray" problem. If you see a question asking for the "maximum sum of a subarray of size K," your instinct might be to use nested loops.
However, that approach is often too slow (O(N²)) and will cause a "Time Limit Exceeded" error on large test cases. Today, I'll explain the Sliding Window technique, which optimizes this to linear time (O(N)).
The Problem
Given an array of integers, find the maximum sum of a subarray of size 'k'.

1. The Naive Approach (Don't do this)
The intuitive way is to calculate the sum for every possible subarray.
Python
def max_sum_naive(arr, k):
max_sum = 0
# Loop through the array
for i in range(len(arr) - k + 1):
current_sum = 0
# Re-calculate sum for every window
for j in range(i, i + k):
current_sum += arr[j]
max_sum = max(max_sum, current_sum)
return max_sum

Why this fails: If k is large, we are re-adding the same numbers over and over again.

2. The Sliding Window Approach
Imagine a window frame of size k sitting on the array. To move the window one step to the right, we don't need to recalculate everything. We simply:
Subtract the element that is leaving the window (the one on the left).
Add the element that is entering the window (the one on the right).

3. The Optimized Code
Python

`def max_sum_sliding_window(arr, k):
# Edge case
if len(arr) < k:
return -1

# Calculate sum of the very first window
window_sum = sum(arr[:k])
max_sum = window_sum

# Slide the window across the rest of the array
for i in range(len(arr) - k):
    # Subtract the previous element, add the next element
    window_sum = window_sum - arr[i] + arr[i + k]
    max_sum = max(max_sum, window_sum)

return max_sum`
Enter fullscreen mode Exit fullscreen mode
  1. Complexity Analysis Naive Approach: O(N x K). If K is close to N, this becomes O(N²). Sliding Window: O(N). We traverse the array exactly once.

Conclusion
The Sliding Window technique is a fundamental pattern for arrays and strings. By avoiding redundant calculations, we reduced the complexity significantly. In an interview, this optimization is the difference between passing and failing.

Top comments (0)