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.
- Use a sliding window (
leftandrightpointers). - Expand
rightand add tocurrentSum. - While
currentSum >= target:- Update
minLength. - Subtract
nums[left]and advanceleft.
- Update
- Print the
minLength. If no such subarray exists, print 0.
01EXAMPLE 1
Input
nums=[2,3,1,2,4,3], target=7Output
2Explanation: [4,3] is the smallest.
Constraints
- Solve in O(n) time.
ArraysSliding Window
JavaScriptSystem handles I/O — write your function only
Loading...
1 Hidden
Input Arguments
nums[2,3,1,2,4,3]
target7
Expected Output
2
Click RUN to test your solution