MEDIUM Sliding Window

209. Minimum Size Subarray Sum

๐Ÿ“– Problem

Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing
  • โ€ขString/array indexing
  • โ€ขSet/Map frequency counting
  • โ€ขPointer movement invariants

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation
  • โ€ขApply Sliding Window reasoning pattern
  • โ€ขApply Two Pointers reasoning pattern

๐Ÿ’ก Approach

  • โ†’ Use sliding window with left and right pointers
  • โ†’ Expand window by moving right pointer
  • โ†’ When sum >= target, shrink from left and track minimum length
  • โ†’ All numbers are positive, so shrinking won't increase sum
  • โ†’ Time: O(n), Space: O(1)

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขUse sliding window with left and right pointers
  • โ€ขExpand window by moving right pointer
  • โ€ขWhen sum >= target, shrink from left and track minimum length

Common Pitfalls

  • โ€ขAll numbers are positive, so shrinking won't increase sum
  • โ€ขTime: O(n), Space: O(1)

๐Ÿงช Test Cases

Hidden tests on submit: 2

Test Case 1
Not run
Input:
minSubArrayLen(7, [2,3,1,2,4,3]);
Expected:
2
Test Case 2
Not run
Input:
minSubArrayLen(4, [1,4,4]);
Expected:
1
Test Case 3
Not run
Input:
minSubArrayLen(11, [1,1,1,1,1,1,1,1]);
Expected:
0

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit