unemployed.dev☕ Support
leetcode/sliding-window
Pattern 02

Sliding Window

Find the best contiguous subarray or substring without recalculating from scratch.

When to use

Use when the problem asks for a best/longest/shortest subarray or substring. The word 'contiguous' is a strong signal. Also when you need to track a running count or frequency over a range.

Core intuition

Keep a window over a continuous range. Expand by moving the right pointer. Shrink by moving the left pointer when the window becomes invalid. Track the best answer while you slide.

Template

def sliding_window(s):
    left = 0
    counts = {}
    best = 0
    for right in range(len(s)):
        counts[s[right]] = counts.get(s[right], 0) + 1
        while window_is_invalid(counts):
            counts[s[left]] -= 1
            if counts[s[left]] == 0:
                del counts[s[left]]
            left += 1
        best = max(best, right - left + 1)
    return best

Suggested problems

Key takeaways
  • Think 'contiguous chunk' of array or string
  • Grow the window by moving right pointer
  • Shrink the window by moving left pointer when invalid
  • Track the best answer as you slide
  • Use a hashmap when counts or frequencies matter
You'll see this when...
  • Longest substring / subarray with some constraint
  • Shortest window containing all characters
  • Maximum sum subarray of size k
  • Find a permutation inside a string
  • Any problem with 'at most k distinct' or 'without repeating'