Algorithms: The Sliding Window Pattern
February 02, 2025
1 min read
0 views
Stop solving array problems with nested loops. Just stop. 🛑
The Problem
Given an array [1, 2, 3, 4, 5], find the maximum sum of 2 consecutive elements.
Naive Way (O(N^2)): You calculate (1+2), then (2+3), then (3+4)... using a nested loop.
Sliding Window (O(N)): Imagine a window frame of size 2.
- Start at
[1, 2]. Sum = 3. - Slide the window right.
- To get the new sum, you don't need to recalculate everything. You just subtract the element leaving (1) and add the element entering (3).
Python
def max_sum(arr, k):
window_sum = sum(arr[:k])
max_val = window_sum
for i in range(len(arr) - k):
window_sum = window_sum - arr[i] + arr[i+k]
max_val = max(max_val, window_sum)
return max_val
Why it matters?
In an interview, O(N^2) fits for N=1000. But for N=1,000,000 (which is real life data), O(N^2) will crash the server. O(N) will run instantly.
Similar Posts
Django: Signals vs Overriding Save
Sep 14, 2025
Python: The 'with' Statement
Aug 21, 2025
Security: SQL Injection in 2025
Jun 03, 2025