Sliding Window Technique

Learn how the sliding window technique efficiently computes the maximum sum of a subarray of fixed length, reducing time complexity from O(n²) to O(n) with constant space.

The Problem

Given an array of integers and a number, find the maximum sum of any subarray of length num. This problem is ideal for demonstrating the sliding window technique, which optimizes nested loops into a single pass.

Example:

maxSubarraySum([2, 6, 9, 2, 1, 8, 5, 6, 3], 3); // Returns 19 (from subarray [8, 5, 6])
js

Approach 1: Brute Force (Naive)

function maxSubarraySum(arr, num) {
  if (arr.length < num) return null;
  let max = -Infinity;
  for (let i = 0; i <= arr.length - num; i++) {
    let temp = 0;
    for (let j = 0; j < num; j++) {
      temp += arr[i + j];
    }
    max = Math.max(max, temp);
  }
  return max;
}
js

Explanation:

  1. Outer loop iterates until reaching arr.length - num, to prevent running out of the array in the inner loop
  2. Inner loop sums num number of elements starting from the current outer loop index
  3. Compare each window’s sum to find the maximum.

Approach 2: Sliding Window (Optimized)

function maxSubarraySum(arr, num) {
  if (arr.length < num) return null;
  let max = 0;
  let temp = 0;

  for (let i = 0; i < num; i++) {
    max += arr[i];
  }

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

  return max;
}
js

Explanation:

  1. Initial window: Sum the first num elements.
  2. Sliding logic:
  • Subtract the outgoing element (left edge of the previous window).
  • Add the incoming element (new right edge).
  1. Efficiency: Reuses the previous sum to avoid recalculating from scratch.

Performance Comparison

ApproachTime ComplexitySpace ComplexityBest ForNotes
Sliding WindowO(n)O(1)Large datasetsMost efficient solution
Brute ForceO(n²)O(1)Small arrays, simplicityEasy to implement but slow

Conclusion

The sliding window technique is a smart way of avoiding recalculation, reducing time complexity from O(n²) to O(n) while using constant space. It’s a powerful technique for optimizing problems involving contiguous sequences.

Last updated: August 21, 2025

⚡ Who am i to talk about this? ⚡

Honestly i am no one, i've just been coding for 3 years now and i like to document every solutions to every problem i encounter. Extracting as much code snippets and tutorials i can so that if i ever need it again i just have to pop back here and get a quick refresher.

Feel free to me through this learning journey by providing any feedback and if you wanna support me: