Clean Markup

Solving Subarray Problems with the Sliding Window Pattern in JavaScript

Solving Subarray Problems with the Sliding Window Pattern in JavaScript

Many coding interview and data processing questions involve finding contiguous subarrays or substrings that satisfy a specific condition—such as finding the maximum sum of k consecutive numbers or the longest substring without repeating characters.

A naive approach evaluates every possible subarray using nested loops, incurring an (O(n imes k)) or (O(n^2)) time complexity. The Sliding Window pattern maintains a running window and adjusts its boundaries, lowering execution to linear (O(n)) time.

Example

Find the maximum sum of any contiguous subarray of size k:

const nums = [2, 1, 5, 1, 3, 2];
const k = 3;
console.log(maxSubarraySum(nums, k)); // 9 (subarray [5, 1, 3])

Implementation

Instead of recalculating the entire sum from scratch on each step, we slide the window by adding the incoming element and subtracting the outgoing element:

function maxSubarraySum(arr, k) {
  if (arr.length < k) return null;

  let maxSum = 0;
  let windowSum = 0;

  // Initialize the first window
  for (let i = 0; i < k; i++) {
    windowSum += arr[i];
  }
  maxSum = windowSum;

  // Slide the window across the rest of the array
  for (let i = k; i < arr.length; i++) {
    windowSum += arr[i] - arr[i - k];
    maxSum = Math.max(maxSum, windowSum);
  }

  return maxSum;
}

Complexity

Main Point: The Sliding Window technique avoids redundant recalculations in contiguous array problems by adding new entries and dropping stale ones in (O(1)) time.

Credits

Photo by Luca Bravo on Unsplash

← Home