Skip to content

Latest commit

 

History

History
 
 

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

README.md

Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.

Example: 

Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.
Follow up:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n). 

Companies:
Goldman Sachs, Facebook, Microsoft

Related Topics:
Array, Two Pointers, Binary Search

Similar Questions:

Solution 1. Sliding Window

// OJ: https://leetcode.com/problems/minimum-size-subarray-sum/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums) {
        int sum = 0, i = 0, j = 0, N = nums.size(), ans = INT_MAX;
        while (j < N) {
            while (j < N && sum < s) sum += nums[j++];
            if (sum < s) break;
            while (i < j && sum >= s) sum -= nums[i++];
            ans = min(ans, j - i + 1);
        }
        return ans == INT_MAX ? 0 : ans;
    }
};

Solution 2. Sliding Window

// OJ: https://leetcode.com/problems/minimum-size-subarray-sum/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    int minSubArrayLen(int s, vector<int>& A) {
        int i = 0, N = A.size(), ans = N + 1, sum = 0;
        for (int j = 0; j < N; ++j) {
            sum += A[j];
            while (sum >= s) {
                ans = min(ans, j - i + 1);
                sum -= A[i++];
            }
        }
        return ans == N + 1 ? 0 : ans;
    }
};