Skip to main content

Sliding Window Pattern

What is Sliding Window?

The Sliding Window pattern is used to perform a required operation on a specific window size of a given array or linked list, such as finding the longest subarray containing all 1s. Sliding Windows start from the 1st element and keep shifting right by one element and adjust the length of the window according to the problem.

When to use Sliding Window?

  • Problems dealing with contiguous subarrays or sublists
  • Finding maximum/minimum sum of any contiguous subarray of size 'k'
  • Finding longest substring with 'k' distinct characters
  • Finding smallest subarray with a given sum

Types of Sliding Window

Fixed Window Size

  • Window size remains constant throughout
  • Example: Find maximum sum subarray of size K

Variable Window Size

  • Window size can grow or shrink
  • Example: Smallest subarray with sum greater than X

Common Problems

Fixed Window

  1. Maximum Sum Subarray of Size K
  2. First Negative Number in Every Window of Size K
  3. Count Occurrences of Anagrams
  4. Maximum of All Subarrays of Size K

Variable Window

  1. Longest Substring with K Distinct Characters
  2. Longest Substring Without Repeating Characters
  3. Minimum Window Substring
  4. Longest Subarray with Ones after Replacement