When to Use

Pattern triggers

Look for these signals in the problem:

  • "Longest/shortest substring with condition X": When optimizing over contiguous sequences, sliding window explores all candidates by expanding right and contracting left.
  • "Subarray" with sum/product constraints: Fixed or variable windows efficiently track running totals without recalculating from scratch.
  • "At most K distinct" elements: The window contracts when exceeding K, automatically finding the longest valid sequence.
  • "Contiguous" sequence requirement: If the answer must be contiguous elements, sliding window is the natural fit over subsequence approaches.