Minimum Subarray With Required Sum

Moderate
0/80
Average time to solve is 18m
profile
Contributed by
57 upvotes
Asked in companies
MyntraFacebookGoldman Sachs

Problem statement

You have been given an array(ARR) of positive integers and an integer X. You have to find the minimum length subarray such that the sum of all of its elements is strictly greater than the given integer X.

Note:
A subarray is a contiguous block of elements that can be formed by deleting some (possibly zero) elements from the beginning or the end of the original array. 
For example :
If the given array is [1, 2, 3, 4, 5], then [2, 3, 4], [1, 2], [5] are some subarrays while [1, 3], [2, 3, 5] are not.

If there are multiple subarrays with minimum length, find one which appears earlier in the array (i.e. subarray that starts with lower index).

If there is no such subarray, print an empty line.
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of input contains two integers 'N' and 'X' separated by a single space. 'N' represents the size of the given array/list and 'X' represents the given integer.

The second line of input contains 'N' single space-separated integers representing the elements of the array/list.
Output Format :
The only line of output contains single space-separated elements of the minimum length subarray.

You do not need to print anything explicitly, it has already been taken care of.
Constraints :
1 <= N <= 5 * 10^5
1 <= X <= 10^9
1 <= ARR[i] <= 10^9

Time Limit: 1 sec
Sample Input 1:
4 13
13 7 6 12
Sample Output 1:
13 7
Explanation For Sample Input 1:
Out of all the subarrays, we have [13, 7] and [6, 12] with minimum length of 2 and sum of their elements greater than X = 13. As the starting index of [13, 7] is lower, we print it as the output.
Sample Input 2:
5 6
1 2 3 4 5
Sample Output 2:
3 4
Hint

Try to check the sum of every subarray naively.

Approaches (3)
Naive Solution

We can check every subarray of the array/list if it’s sum is greater than X(given integer) or not. To do this, we traverse for every possible start and endpoint of the subarray using two nested loops. We will keep updating the ‘sum’ while expanding our endpoint. Out of all the valid(sum greater than X) subarrays, we pick the minimum length subarray.

Time Complexity

O(N^2),  Where N is the number of elements in the array/list.

 

In the worst case, we traverse for every possible start and endpoint of the subarray, which will result in O(N^2) time complexity.

Space Complexity

O(1)

 

No extra space is used.

Code Solution
(100% EXP penalty)
Minimum Subarray With Required Sum
Full screen
Console