Sliding Window

Welcome to the Sliding Window section of JDCodebase! Sliding Window is a powerful pattern to reduce nested loops by maintaining a running window over the data. It's widely used for subarray, substring, and optimization problems in linear time.

What You’ll Learn

  • Fixed and dynamic window size techniques
  • Tracking sum, max/min, or frequency within a window
  • Shrinking/growing the window to meet constraints
  • Using hash tables or counters to track window content
  • Optimizing brute force solutions to O(n)

Common Sliding Window Patterns

Fixed-size Window: Use two pointers to maintain a fixed-size subarray.
Before: [1, 2, 3, 4, 5], k = 3
Code: let maxSum = 0;
  for (let i = 0; i < k; i++) maxSum += arr[i];
  let windowSum = maxSum;
  
  for (let i = k; i < arr.length; i++) {
    windowSum += arr[i] - arr[i - k];
    maxSum = Math.max(maxSum, windowSum);
  }
After: Max sum of subarray of size k
Dynamic-size Window: Shrink or expand window based on condition.
Before: arr = [2, 3, 1, 2, 4, 3], target = 7
Code: function minSubArrayLen(target, arr) {
            let left = 0, sum = 0, minLen = Infinity;
          
            for (let right = 0; right < arr.length; right++) {
              sum += arr[right];
          
              while (sum >= target) {
                minLen = Math.min(minLen, right - left + 1);
                sum -= arr[left++];
              }
            }
          
            return minLen === Infinity ? 0 : minLen;
          }
After: 2 (subarray [4, 3])

Try This Example

Find the maximum sum of a subarray with length k.

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

Input: arr = [2, 1, 5, 1, 3, 2], k = 3

Expected Output: 9