Core Module
12 min forge

Sliding Window

Effortlessly solve subarray and substring problems by maintaining a window that slides across the collection.

πŸͺŸ Sliding Window: Optimal Subarrays

The sliding window technique is used to find a sub-segment (subarray or substring) that satisfies a specific condition. It transforms nested loops ($O(n^k)$) into a single pass ($O(n)$) by moving a "window" of elements instead of recomputing everything.

πŸ’‘ The Logic (ELI5)

Imagine you're watching a long train pass by a small window:

  1. You can only see a few cars (the window) at a time.
  2. To see the next car, you don't need a new train.
  3. One car leaves the left side of your view, and one car enters the right side.
  4. You only need to check the car that just arrived and the one that just left.

πŸ” The Deep Dive

Types of Windows

  1. Fixed Size: The window width $K$ is constant. You move the window by 1 step every time.
    • Example: Highest average of any 5 consecutive days.
  2. Dynamic (Variable) Size: The window grows or shrinks based on the contents.
    • Example: Smallest subarray with a sum greater than $X$.

The Algorithm Pattern

  • Step 1: Initialize two pointers left=0, right=0.
  • Step 2: Expand the window by moving right and adding the new element to our "state" (e.g., current sum).
  • Step 3: If the condition is broken (or met, depending on the problem), shrink the window from the left until the condition is valid again.
  • Step 4: Update your global answer (max, min, count).

πŸ› οΈ Code Forge: Maximum Sum of Subarray Size K

javascript Standard
/** * Finding the maximum sum of any contiguous subarray of size K. * Brute force: O(n*K) | Sliding Window: O(n) */ function maxSumFixedWindow(arr, k) { let maxSum = 0; let currentSum = 0; // 1. Initial window sum for the first 'k' elements for (let i = 0; i < k; i++) { currentSum += arr[i]; } maxSum = currentSum; // 2. Slide the window for (let i = k; i < arr.length; i++) { /** * Subtract the element that's leaving (arr[i - k]) * Add the element that's entering (arr[i]) */ currentSum = currentSum - arr[i - k] + arr[i]; maxSum = Math.max(maxSum, currentSum); } return maxSum; } // Example const arr = [2, 1, 5, 1, 3, 2]; const k = 3; console.log(maxSumFixedWindow(arr, k)); // 9 (Subarray: [5, 1, 3])

🎯 Interview Pulse

Key Indicators

  • "Contiguous" Subarray/Substring: This is the biggest hint.
  • Minimum/Maximum/Longest/Shortest: Optimization problems.
  • Target Sum/Unique Characters: Constraints on the subarray.

Must-Practice Problems

  • Longest Substring Without Repeating Characters: Classic dynamic window problem.
  • Minimum Window Substring: A challenging high-tier interview question.
  • Fruit Into Baskets: A creative variant of the sliding window.
  • Permutation in String: Using hash maps with a window.