Sliding Window Technique - aloalgo.com

Sliding Window Technique

The sliding window technique transforms brute-force O(n²) solutions into elegant O(n) ones. It's one of the most powerful patterns for array and string problems, and once you recognize it, you'll see it everywhere.

1. When to Use Sliding Window

Look for these signals:
  • The problem involves a contiguous sequence (subarray or substring)
  • You need to find min/max/count of something in that sequence
  • Keywords: "contiguous", "substring", "subarray", "consecutive", "window"
Classic examples:
  • Maximum sum of k consecutive elements
  • Longest substring without repeating characters
  • Smallest subarray with sum ≥ target
  • Find all anagrams in a string

2. The Two Types

Fixed WindowVariable Window
Window SizeConstant (given as k)Changes based on condition
PointersMove togetherMove independently
Typical Ask"Of size k...""Longest/shortest that..."
ExampleMax sum of k elementsLongest substring without repeats

3. Fixed-Size Window

The window size is given. Slide it across the array, updating your answer as you go.

Template

Example: Maximum Sum of K Consecutive Elements

Idea: Initialize the sum of the first k elements, then slide the window by adding the next element and removing the first element of the previous window.
  • Time: O(n)
  • Space: O(1)

Example: Find All Anagrams

Idea: Use a fixed window of size equal to the pattern length. Track character frequencies with a hashmap and compare against the pattern's frequency map as the window slides.
  • Time: O(n) where n is the length of the string
  • Space: O(1) - fixed alphabet size

4. Variable-Size Window

The window expands and contracts based on a condition. This is the more powerful (and trickier) pattern.

Template: Find Longest

Template: Find Shortest


Key difference:
  • Longest: Expand freely, shrink when invalid, update after shrinking
  • Shortest: Expand until valid, shrink while valid, update while shrinking

5. Classic Problems

Longest Substring Without Repeating Characters

Idea: Expand the window by adding characters to a set. When a duplicate is found, shrink from the left until the duplicate is removed. Track the maximum window size seen.
  • Time: O(n)
  • Space: O(min(n, alphabet size))

Minimum Size Subarray Sum

Find the shortest subarray with sum ≥ target.

Longest Substring with At Most K Distinct Characters

Maximum Consecutive Ones III

Longest subarray of 1s if you can flip at most k zeros.

6. Sliding Window with HashMap

Many problems require tracking character/element frequencies. Use a hashmap to maintain counts.

Minimum Window Substring

Find the smallest window in s that contains all characters of t.

7. The Mental Model

Think of sliding window as a caterpillar:
  1. Expand the right side (head moves forward)
  2. Check if window satisfies the condition
  3. Contract the left side if needed (tail catches up)
  4. Update the answer
The key insight: both pointers only move forward. This is why the algorithm is O(n)—each element is added once and removed at most once.

8. Common Mistakes

MistakeProblemFix
Updating result at wrong timeMissing valid windowsLongest: after shrink. Shortest: during shrink.
Off-by-one in window sizeWrong answerWindow size = right - left + 1
Not cleaning up hashmapWrong distinct countDelete key when count reaches 0
Using if instead of whileIncomplete shrinkingAlways use while for contraction

9. Complexity

TypeTimeSpace
Fixed windowO(n)O(1) or O(k)
Variable windowO(n)O(1) or O(unique elements)
With hashmapO(n)O(alphabet size)

Both pointers traverse the array once, so total operations = O(2n) = O(n).

10. Practice Problems

Variable WindowRelated Patterns

Final Thoughts

Sliding window is really about maintaining a valid state as you traverse. The window is just the visualization—what matters is knowing what to track, when to expand, and when to contract. Master this pattern and you'll solve a huge category of problems with the same mental framework.
Was this helpful?
© 2026 aloalgo.com. All rights reserved.