Problem Description
Given an array of positive integers nums and a positive integer target, find the minimal length of a contiguous subarray whose sum is greater than or equal to target. If no such subarray exists, return 0.
Key Insights
- All numbers are positive, which allows for a sliding window approach.
- A sliding window maintains a dynamic range [left, right] that expands or contracts to find candidate subarrays.
- The window is expanded until the sum meets/exceeds the target, then contracted to seek the minimal candidate.
- An O(n) solution is achievable with the sliding window technique; an alternative O(n log n) solution exists using prefix sums and binary search.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Solution
We use the sliding window approach:
- Initialize two pointers, left and right, and a variable to maintain the current window sum.
- As you iterate with the right pointer, add the current element to the window sum.
- While the window sum is greater than or equal to target, try to reduce the window size by moving the left pointer forward and update the minimal length found.
- If no valid window is found throughout the loop, return 0. This method works efficiently because adding an element increases the sum and removing it decreases the sum, so we maintain validity within a single pass.