Find all subarrays with sum equal to number? JavaScript (Sliding Window Algorithm)

We are given an array of numbers and a target sum. Our job is to write a function that returns an array of all the subarrays which add up to the target number using the sliding window algorithm.

For example:

const arr = [23, 5, 1, 34, 12, 67, 9, 31, 6, 7, 27];
const sum = 40;

Should find these subarrays that sum to 40:

[ [ 5, 1, 34 ], [ 9, 31 ], [ 6, 7, 27 ] ]

The Sliding Window Algorithm

The sliding window algorithm is perfect for finding subarrays that satisfy certain criteria. It maintains a window (subarray) that dynamically expands or contracts based on the current sum compared to the target.

23 5 1 34 12 67 start end Window: [5, 1, 34] = 40

How the Algorithm Works

The algorithm uses two pointers (start and end) to maintain a sliding window:

  • If current sum < target: Expand window by moving end pointer
  • If current sum > target: Shrink window by moving start pointer
  • If current sum = target: Record the subarray and slide the window

Implementation

const arr = [23, 5, 1, 34, 12, 67, 9, 31, 6, 7, 27];
const targetSum = 40;

const findSubarraysWithSum = (arr, targetSum) => {
    const result = [];
    let start = 0, end = 0, currentSum = 0;
    
    while (end  targetSum) {
            // Shrink window
            currentSum -= arr[start];
            start++;
        } else if (currentSum === targetSum) {
            // Found a valid subarray
            result.push(arr.slice(start, end));
            // Slide window
            currentSum -= arr[start];
            start++;
        } else {
            // End of array reached
            break;
        }
    }
    
    return result;
};

console.log(findSubarraysWithSum(arr, targetSum));
[ [ 5, 1, 34 ], [ 9, 31 ], [ 6, 7, 27 ] ]

Step-by-Step Execution

Let's trace through the algorithm with a smaller example:

const smallArr = [1, 2, 3, 4];
const target = 5;

console.log("Finding subarrays with sum", target);
console.log("Array:", smallArr);

// Trace execution
let start = 0, end = 0, sum = 0;
const results = [];

console.log("\nStep-by-step:");
while (end  target) {
        sum -= smallArr[start];
        console.log(`  Removed ${smallArr[start]}, sum now: ${sum}`);
        start++;
    } else if (sum === target) {
        const subarray = smallArr.slice(start, end);
        results.push(subarray);
        console.log(`  Found subarray: [${subarray}]`);
        sum -= smallArr[start];
        start++;
    } else {
        break;
    }
}

console.log("\nResult:", results);
Finding subarrays with sum 5
Array: [ 1, 2, 3, 4 ]

Step-by-step:
Window: [0, 0), Sum: 0
  Added 1, sum now: 1
Window: [0, 1), Sum: 1
  Added 2, sum now: 3
Window: [0, 2), Sum: 3
  Added 3, sum now: 6
Window: [0, 3), Sum: 6
  Removed 1, sum now: 5
Window: [1, 3), Sum: 5
  Found subarray: [2,3]
  Removed 2, sum now: 3
Window: [2, 3), Sum: 3
  Added 4, sum now: 7
Window: [2, 4), Sum: 7
  Removed 3, sum now: 4
Window: [3, 4), Sum: 4

Result: [ [ 2, 3 ] ]

Time Complexity

The sliding window algorithm achieves O(n) time complexity because each element is visited at most twice (once when expanding, once when shrinking the window).

Conclusion

The sliding window technique efficiently finds all subarrays with a target sum in linear time. It's ideal for problems involving contiguous elements that need to satisfy specific criteria.

Updated on: 2026-03-15T23:18:59+05:30

689 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements