Minimum Size Subarray Sum - Array - Medium - LeetCode
💻 coding

Minimum Size Subarray Sum - Array - Medium - LeetCode

1 min read 171 words
1 min read
ShareWhatsAppPost on X
  • 1The problem requires finding the minimal length of a contiguous subarray with a sum greater than or equal to a given integer s.
  • 2An example shows that for s = 7 and nums = [2,3,1,2,4,3], the minimal subarray length is 2, corresponding to [4,3].
  • 3The optimal solution has a time complexity of O(n) and a space complexity of O(1), with a follow-up challenge for O(n log n) complexity.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The problem requires finding the minimal length of a contiguous subarray with a sum greater than or equal to a given integer s."

Minimum Size Subarray Sum - Array - Medium - LeetCode

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).

public class Solution {
 public int MinSubArrayLen(int s, int[] nums) {
 if (nums.Length == 0)
 {
 return 0;
 }

 int start = 0;
 int end = 0;
 int sum = nums[0];
 int min = int.MaxValue;
 while (true)
 {
 if (sum >= s)
 {
 if (end - start+1 < min)
 {
 min = end - start+1;
 }
 sum -= nums[start];
 start++;
 }
 else
 {
 end++;
 if(end > nums.Length - 1)
 {
 break;
 }
 sum += nums[end]; 
 }
 }

 return min == int.MaxValue ? 0 : min;
 }
}

Time Complexity: O(n)

Space Complexity: O(1)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 18 November 2020 · 1 min read · 171 words

Part of AskGif Blog · coding

You might also like