Skip to Content

When is the sliding window the right pattern?

Category: DSA Patterns

Answer

Sliding window works on substrings/subarrays where you need a sum, a count, or a property (no repeats, all chars present). You maintain L and R pointers and a window-state dict; advance R to grow, advance L to shrink on violation. O(N) overall because each element enters and leaves once.

Concrete examples from the fca project context

Example 1

Max sum subarray length K: window sum updates as you slide.

Example 2

Longest substring without repeating: window dict of last seen index, L jumps.

Example 3

Minimum window substring: shrink the window as long as all required chars are present.

Data flow / flow chart

arr -> grow R until condition met -> shrink L until condition broken -> record answer -> repeat

Takeaway

Sliding window when you fix a window size or a condition. Two-pointer when ordered pairs.