Sliding Window

intermediate35 min

Sliding Window Technique

A sliding window maintains a contiguous segment while you move its ends—ideal when the problem asks for the best or all subarrays of a given length, or the shortest segment that meets a condition.

Types of Sliding Windows

  • Fixed Size Window: Window size is constant
  • Variable Size Window: Window size changes based on conditions
  • Dynamic Window: Window expands and contracts

Fixed Size Window Example

Variable Size Window Example

Dynamic Window with HashMap

Common Applications

  • Subarray Problems: Maximum/minimum sum, average
  • Substring Problems: Longest/shortest substring with conditions
  • Frequency Problems: Substrings with specific character frequencies
  • Optimization: Reduce time complexity from O(n²) to O(n)