Minimum Size Subarray Sum Java Solution - The Coding Shala

Home >> Interview Question >> Minimum size subarray sum

Minimum Size Subarray Sum


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.


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.

Minimum Size Subarray Sum Java Solution

Use two pointers.

class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        int len = Integer.MAX_VALUE, sum = 0, left=0;
        for(int i = 0; i<nums.length; i++){
            sum += nums[i];
            while(sum >= s){
                len = Math.min(len, i+1-left);
                sum -= nums[left];
        return len == Integer.MAX_VALUE ? 0 : len;

Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.


Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Single Number 3 LeetCode Solution - The Coding Shala

LeetCode - Number of Good Pairs Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Java Method Overloading - The Coding Shala