Description:
Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous
subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.
Input: target = 7, nums = [2,4,1,2,4,3] Output: 2
Input: target = 15, nums = [2, 2, 2, 2, 2] Output: 0
This problem is efficiently solved using the sliding window technique without requiring any special data structures. The approach can be summarized as follows:
- Initialize two pointers,
leftandright, both at0. These represent the current window boundaries. - Initialize a variable
totalto0to keep track of the sum of the current window. - Initialize
minLengthto a very large number (e.g., infinity) to represent the length of the smallest valid subarray found so far. - Iterate through the array with the
rightpointer:- Add
nums[right]tototal. - While
totalis greater than or equal totarget:- Update
minLengthto the smaller value between the currentminLengthand the window size (right - left + 1). - Subtract
nums[left]fromtotaland move theleftpointer forward to try and find a smaller valid window.
- Update
- Add
- Continue until the
rightpointer reaches the end of the array. - If
minLengthis still infinity (meaning no valid subarray was found), return0. Otherwise, returnminLength.
-
Time Complexity:
O(n)
The array is traversed at most twice (once by each pointer), resulting in linear time complexity. -
Space Complexity:
O(1)
No additional data structures are used; only a fixed number of variables are maintained.