LeetCode – Minimum Size Subarray Sum (Java)

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

For example, given the array [2,3,1,2,4,3] and s = 7, the subarray [4,3] has the minimal length of 2 under the problem constraint.

Analysis

We can use 2 points to mark the left and right boundaries of the sliding window. When the sum is greater than the target, shift the left pointer; when the sum is less than the target, shift the right pointer.

Java Solution - two pointers

A simple sliding window solution.

public int minSubArrayLen(int s, int[] nums) {
    if(nums==null || nums.length==1)
        return 0;
 
    int result = nums.length;
 
    int start=0;
    int sum=0;
    int i=0;
    boolean exists = false;
 
    while(i<=nums.length){
        if(sum>=s){
            exists=true; //mark if there exists such a subarray 
            if(start==i-1){
                return 1;
            }
 
            result = Math.min(result, i-start);
            sum=sum-nums[start];
            start++;
 
        }else{
            if(i==nums.length)
                break;
            sum = sum+nums[i];
            i++;    
        }
    }
 
    if(exists)
        return result;
    else
        return 0;
}

Similarly, we can also write it in a more readable way.

public int minSubArrayLen(int s, int[] nums) {
    if(nums==null||nums.length==0)
        return 0;
 
    int i=0; 
    int j=0;
    int sum=0;
 
    int minLen = Integer.MAX_VALUE;
 
    while(j<nums.length){
        if(sum<s){
            sum += nums[j];
            j++;        
        }else{
            minLen = Math.min(minLen, j-i);
            if(i==j-1)
                return 1;
 
            sum -=nums[i];
            i++;
        }
    }
 
    while(sum>=s){
        minLen = Math.min(minLen, j-i);
 
        sum -=nums[i++];
    }
 
    return minLen==Integer.MAX_VALUE? 0: minLen;
}
Category >> Algorithms >> Interview  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>

  1. rjb on 2015-6-20

    shoulldnt we have sorted the array before ?

  2. srrm on 2015-7-17

    Yeah, looks like a sort is required.

    For instance, array[-1, 1, 2, 1, 2, 1], sum = 4, returns 3 based on above algorithm.

    But the same algo with the array being sorted returns the correct answer 2, as the sum of array [2, 2] is >= 4.

  3. Hung Vu on 2015-8-1

    No. Sorting is not allowed here since that will alter the original arrangement of the numbers in the array. There is an implicit requirement that the initial order of the numbers in the array be preserved. Sorting will violate that requirement.

  4. Varun on 2015-10-10

    Dude, did you not read the problem? It says n positive integers! In what world is -1 a positive integer??

  5. NewGuest on 2015-12-13

    For input int a[]={2,3,1,1,8,3} and sum 7 it is giving wrong results

  6. airjordan919 on 2016-4-3

    I want to share my solution here. I think it’s more concise 🙂

    public int minSubArrayLen(int s, int[] nums) {
    if (nums == null || nums.length == 0 || s <= 0) return 0;
    int min = Integer.MAX_VALUE;
    int i = 0, sum = 0;
    for (int j = 0; j = s) {
    min = Math.min(min, j – i + 1);
    sum -= nums[i++];
    }
    }
    return min == Integer.MAX_VALUE ? 0 : min;
    }

  7. NewGuest on 2016-4-23

    Gives wrong result for [4,1,2,2,3,3] and s = 7. The result expected is 2 but it gives 3

  8. Noe Alejandro Perez Domínguez on 2016-9-12

    My solution using Java’s cousin. Scala.

    def minSizeSubArraySum(xs: List[Int], s: Int): Int = {

    def loop(step: Int): Int =
    if (xs.sliding(step).toList.exists(_.sum >= s)) step
    else loop(step + 1)

    if (xs.sum >= s) loop(1) else 0

    }

  9. Noe Alejandro Perez Domínguez on 2016-9-12

    My solution using Java’s cousin. Scala.

    def minSizeSubArraySum(xs: List[Int], s: Int): Int = {

    def loop(step: Int): Int =
    if (xs.sliding(step).toList.exists(_.sum >= s)) step
    else loop(step + 1)

    if (xs.sum >= s) loop(1) else 0

    }

  10. mallika on 2016-10-3

    Hi is my solution right?

    public static int minSizeSubArray(int[] arrA, int target){
    if(arrA == null || arrA.length == 0){
    throw new IllegalArgumentException(“”);
    }
    int index = 0;
    int result = Integer.MAX_VALUE;
    int sum = 0;
    for(int i = 0; i target){
    sum = sum – arrA[index];
    index++;
    }
    if(sum == target){
    result = Math.min(result, (i – index)+1);
    sum = sum – arrA[index];
    index++;
    }
    }
    return result;
    }

  11. Rishab Ghanti on 2017-3-1

    What is the time complexity of the above first code? Will it be O(n)?

Leave a comment

*