Minimum Size Subarray Sum

Minimum Size Subarray Sum (Smallest subarray whose sum is greater than or equal to target).

Given an array of positive integers and a positive number k. Find the smallest contiguous subarray whose sum is either greater than or equal to k. If no subarray is found then return 0.

For example –

Example 1 –

  Input :  {7, 2, 1, 1, 6, 5},  k = 11

Output:  2 ( subarray {6, 5} has the minimum length )

Example 2 –

  Input : {1, 4, 3},   k = 12

Output: 0 (No subarray is possible)

Minimum Size Subarray Sum


In this tutorial, I am going to discuss multiple approaches and their time complexities to solve this problem.

Method 1 : By using brute force approach

The easiest approach is to form all the subarrays of the array whose sum is greater than or equal to k. To form all the subarrays we need to use two for loops.

From the outer loop we pick each element of an array one by one. And from the inner loop we keep adding the elements (starting from that index) till it is less than the value of k.

Whenever sum of elements between current start and end becomes equal or greater than the given number, update the min length value.

The time complexity of this approach is O(n^2).

We have solved this problem in O(n^2). Now, let’s think how we can solve this problem efficiently. How we can improve our time complexity?

Minimum Size Subarray Sum – Java Code

How we can find smallest subarray with sum greater than or equal to the given value?

We can solve this problem using two pointers in O(n) time complexity. Here are the following steps –

i) Declare three pointers start, sum and minLength. Initialize start and sum with zero and minLength with integer max value.

start = 0, sum = 0, minLength = Integer.MAX_VALUE

ii) Start traversing an array and do the following operations.

a) Add current array index value to the sum variable.

b) while sum is greater than or equal to k. Then, update min length and subtract arr[start] value from sum variable. Also increment the value of start index.

Also, I have added the video tutorial at the end of this post.

Programming Video Tutorials

Find triplet with given sum in an array

Find maximum sum of a subarray of size k

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.