This post shows how to find the smallest subarray with a sum greater than or equal to a given target in JavaScript using the Sliding Window technique — another high-frequency variation of the sliding window pattern asked in interviews.

Smallest subarray with sum ≥ target (Sliding Window) in JavaScript:

Explanation:
This is another variable-size sliding window, but working in the opposite direction from the longest-substring problem: here we expand the window by adding elements until the sum meets the target, then shrink it from the left as much as possible while the condition still holds, tracking the smallest window length seen along the way.


JavaScript Program to Find the Smallest Subarray with Sum Greater Than or Equal to Target

function smallestSubarraySum(arr, target) {
  let windowSum = 0;
  let left = 0;
  let minLength = Infinity;

  for (let right = 0; right < arr.length; right++) {
    windowSum += arr[right];

    while (windowSum >= target) {
      minLength = Math.min(minLength, right - left + 1);
      windowSum -= arr[left];
      left++;
    }
  }

  return minLength === Infinity ? 0 : minLength;
}

const numbers = [2, 1, 5, 2, 3, 2];
const target = 7;

console.log("Smallest subarray length with sum >=", target, ":", smallestSubarraySum(numbers, target));

Output:

Smallest subarray length with sum >= 7 : 2

Recognizing when a problem needs a shrinking window versus a fixed or only-growing window is a key interview skill — see more variations of this pattern in our Interview Prep section, or practice similar problems daily with our Problem of the Day.


Frequently Asked Questions About the Smallest Subarray Sum Problem

How is this different from the maximum sum subarray of size K problem?

That problem uses a fixed window size and asks for the best sum within it. This problem has no fixed window size — instead the window grows and shrinks dynamically, and we're looking for the smallest window that satisfies a sum condition.

What happens if no subarray meets the target sum?

The function returns 0, signaling that no valid subarray exists. In a real interview, it's worth clarifying with the interviewer what should be returned in this edge case, since conventions vary (some return -1 instead).

What's the time complexity of this approach?

O(n). Even though there's a nested while loop, the left pointer only moves forward and never resets, so across the entire run the total number of left-pointer moves is bounded by n.