Smallest Subarray for Sum

HardAcc. 82.6%
+45 XP 20

Variable Window Search

Shrink your window from the left as soon as your total meets the target to find the absolute minimum length.

The Assignment

Your function receives nums and target.

  1. Use a sliding window (left and right pointers).
  2. Expand right and add to currentSum.
  3. While currentSum >= target:
    • Update minLength.
    • Subtract nums[left] and advance left.
  4. Print the minLength. If no such subarray exists, print 0.

01EXAMPLE 1

Inputnums=[2,3,1,2,4,3], target=7
Output2

Explanation: [4,3] is the smallest.

Constraints

  • Solve in O(n) time.
ArraysSliding Window
JavaScript
Loading...
1 Hidden

Input Arguments

nums[2,3,1,2,4,3]
target7

Expected Output

2

Click RUN to test your solution