PatternsSliding Window

Sliding Window Pattern

Master problems involving subarrays, substrings, or variable-length windows using this powerful pattern.

27 Problems
4-5 Hours
Easy to Hard

When to Use Sliding Window

Fixed Window Size

When the problem requires a subarray/substring of size k

Dynamic Window Size

When the window can grow/shrink depending on the condition

Max/Min Sum or Length

Finding longest, shortest, or maximum sum windows

Streaming Data

When processing continuous streams of data

Key Insights & Tips

Time Complexity

Usually O(n), efficient for continuous data

Space Efficiency

O(1) to O(n), depending on storage

Common Mistake

Incorrectly shrinking or expanding the window

Pro Tip

Think in terms of window size & boundary conditions

Code Examples

Fixed Size Sliding Window

Find the maximum sum of k consecutive elements

Time: O(n)Space: O(1)
function maxSum(arr: number[], k: number): number {
  let maxSum = 0, windowSum = 0;

  for (let i = 0; i < k; i++) {
    windowSum += arr[i];
  }

  maxSum = windowSum;

  for (let i = k; i < arr.length; i++) {
    windowSum += arr[i] - arr[i - k];
    maxSum = Math.max(maxSum, windowSum);
  }

  return maxSum;
}

Smallest Subarray with Given Sum

Dynamic sliding window to find minimal length subarray with sum ≥ target

Time: O(n)Space: O(1)
function minSubArrayLen(target: number, nums: number[]): number {
  let left = 0, sum = 0, minLen = Infinity;

  for (let right = 0; right < nums.length; right++) {
    sum += nums[right];

    while (sum >= target) {
      minLen = Math.min(minLen, right - left + 1);
      sum -= nums[left++];
    }
  }

  return minLen === Infinity ? 0 : minLen;
}

Longest Substring Without Repeating Characters

Dynamic-size sliding window for string processing

Time: O(n)Space: O(n)
function lengthOfLongestSubstring(s: string): number {
  let seen = new Map<string, number>();
  let left = 0, maxLen = 0;

  for (let right = 0; right < s.length; right++) {
    const char = s[right];

    if (seen.has(char) && seen.get(char)! >= left) {
      left = seen.get(char)! + 1;
    }

    seen.set(char, right);
    maxLen = Math.max(maxLen, right - left + 1);
  }

  return maxLen;
}

Your Progress

Problems Solved0/20
0% Complete20 remaining

Practice Problems

View All

Maximum Sum Subarray of Size K

easy

Longest Substring Without Repeating Characters

medium

Minimum Window Substring

hard

Longest Substring with At Most K Distinct Characters

medium

Sliding Window Maximum

hard

Asked by Companies

GoogleMetaAmazonAdobeMicrosoft

Next Pattern

Ready for the next challenge?

Fast & Slow Pointers