All Patterns

Sliding Window

Maintain a dynamic window over a contiguous subarray or substring to find optimal ranges in O(n) time.

When to use

  • Contiguous subarray/substring
  • Longest/shortest with constraint
  • Fixed-size window aggregation

When NOT to use

  • Non-contiguous elements needed
  • Need to compare all possible subsets

Common traps

  • Forgetting to shrink the window
  • Off-by-one on window boundaries
  • Not tracking window state correctly

Key Invariant

The window always satisfies the problem's constraint — expand right to explore, shrink left to restore validity

Problems (18)

#12Best Time to Buy and Sell Stock
easyFREE
#50Maximum Average Subarray I
easyFREE
#51Find All Anagrams in a String
easy
#31Longest Substring Without Repeating Characters
mediumFREE
#87Minimum Window Substring
medium
#88Permutation in String
medium
#89Fruit Into Baskets
medium
#90Max Consecutive Ones III
medium
#225Minimum Size Subarray Sum
medium
#227Maximum Points You Can Obtain from Cards
medium
#248Longest Repeating Character Replacement
medium
#249Grumpy Bookstore Owner
medium
#251Minimum Number of Flips to Make Binary String Alternating
medium
#252Count Number of Nice Subarrays
medium
#253Maximum Number of Vowels in a Substring of Given Length
medium
#300Find Longest Substring With Even Vowel Counts
medium
#119Sliding Window Maximum
hard
#250Subarrays with K Different Integers
hard