DSA — Techniques

Sliding Window

Maintain a window of elements and slide it across. Add new right element, remove leftmost — reuse previous computation.

— min read
O(n)Time
O(1)Space
FixedVariable Size
Subarr.Substring
Max/Min K
// MAX SUM SUBARRAY OF SIZE k
k =
Set k and Press Run
How It Works
Python Code
Use Cases
Quiz
Practice
01
Build First Window
Sum first k elements.
window_sum = sum(arr[0:k])
02
Slide
Add right element, subtract leftmost.
window_sum += arr[r] - arr[r-k]
03
Track Max
Update max sum each slide.
max_sum = max(max_sum, window_sum)
04
O(n) not O(n*k)
Never recompute entire window sum.
python
def max_subarray_sum(arr, k):
    n = len(arr)
    ws = sum(arr[:k])
    mx = ws
    for i in range(k, n):
        ws += arr[i] - arr[i-k]
        mx = max(mx, ws)
    return mx
Fixed window: Max/min/sum over exactly k elements.
Variable window: Expand right until condition breaks, shrink left to restore.
Max Sum Subarray Longest No-Repeat Substring Min Window Substring Sliding Window Max Fruit Into Baskets
The key operation making Sliding Window O(n):
Progress 0 / 5 solved
5 problems · 4 PBC · 1 Startup
#021 Longest Substring Without Repeating Chars Netflix, Microsoft PBC
#024 Minimum Window Substring Meta, Amazon PBC
#067 Sliding Window Maximum Amazon PBC
#004 Maximum Subarray Meta, Amazon PBC
#016 Maximum Sum Circular Subarray Meesho STARTUP