THN Interview Prep

209. Minimum Size Subarray Sum

At a Glance

  • Topic: sliding-window
  • Pattern: Sliding Window
  • Difficulty: Medium
  • Companies: Google, Amazon, Meta, Goldman Sachs, Microsoft
  • Frequency: High
  • LeetCode: 209

Problem (one-liner)

Given an array of positive integers nums and a target target, return the minimal length of a contiguous subarray whose sum is at least target. Return 0 if none exists.

Recognition Cues

  • Positive integers → window sum monotonic as you extend
  • "Shortest subarray with sum ≥ target"
  • Classic variable-size window with shrink-from-left

Diagram

At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.

Loading diagram…

Approaches

  • Brute force — all subarrays — O(n³) naïve, O(n²) with prefix sums.
  • Better — sliding window — O(n) time / O(1) space for positives.
  • Optimal — same sliding window; not valid if negatives allowed (then prefix sum + deque/monotonic).

Optimal Solution

Go

func minSubArrayLen(target int, nums []int) int {
	left := 0
	sum := 0
	best := len(nums) + 1
	for right := 0; right < len(nums); right++ {
		sum += nums[right]
		for sum >= target {
			width := right - left + 1
			if width < best {
				best = width
			}
			sum -= nums[left]
			left++
		}
	}
	if best == len(nums)+1 {
		return 0
	}
	return best
}

JavaScript

function minSubArrayLen(target, nums) {
	let left = 0;
	let sum = 0;
	let best = nums.length + 1;
	for (let right = 0; right < nums.length; right++) {
		sum += nums[right];
		while (sum >= target) {
			const width = right - left + 1;
			if (width < best) {
				best = width;
			}
			sum -= nums[left];
			left++;
		}
	}
	return best === nums.length + 1 ? 0 : best;
}

Walkthrough

Input: target = 7, nums = [2,3,1,2,4,3]

rightsumshrink while ≥7best
7window [2,3,1,1] too long — shrink left until sum<7record min width

Invariant: for each right, minimal valid window ending at right is found by maximizing left while sum still ≥ target.

Edge Cases

  • Total sum < target → 0
  • Single element equals target
  • Entire array needed

Pitfalls

  • Including zeros or negatives breaks monotonicity — solution template changes
  • Initializing best to zero incorrectly (use sentinel max)

Similar Problems

Variants

  • Sum exactly equals target with non-negative — prefix sum + hashmap count.
  • With negatives — shortest subarray with deque on prefix minima.

Mind-Map Tags

#sliding-window #variable-window #prefix-sum-window #positive-integers #minimum-length

Last updated on

Spotted something unclear or wrong on this page?

On this page