Rahul And Minimum Subarray

Rahul is a programming enthusiast. He is currently learning about arrays/lists. One day his teacher asked him to solve a very difficult problem. The problem was to find the length of the smallest subarray(subarray is a contiguous part of an array/list) in a given array/list ‘ARR’ of size ‘N’ with its sum greater than a given value. If there is no such subarray return 0.

Example: Given an ‘ARR’: [1, 2, 21, 7, 6, 12] and a number ‘X’: 23. The length of the smallest subarray is 2 as the subarray is [21, 7].

Note: Here are multiple subarrays whose sum is greater than ‘X’ such as [1, 2, 21] or [7, 6, 12] but we have to choose the minimum length subarray.

Input Format:
The first line contains a single integer ‘T’ representing the number of test cases. 

The first line of each test case will contain two integers ‘N’ and ‘X’ that denote the size of the ‘ARR’ and the given value respectively.

The second line of each test case contains ‘N’ space-separated integers ‘A[i]’, these are the numbers present in our ‘ARR’.
Output Format:
For each test case, print an integer denoting the length of the minimum subarray whose sum is greater than ‘X’.

Output for every test case will be printed in a separate line.
Note:
You don’t need to print anything; It has already been taken care of.
Constraints:
1 <= T <= 10^2
1 <= N <= 10^3
1 <= X <= 10^9
0 <= A[i] <= 10^9

Time Limit: 1 sec
CodingNinjas
author
2y

Approach 1 (Brute Force) :
In this approach, we make use of an idea based on selection sort.

1) Traverse over the given numsnums array choosing the elements nums[i]. For every such element chosen, we tr...read more

CodingNinjas
author
2y
Brute Force

The basic idea of this approach is to iterate the whole ‘ARR’ from start and find the sum of all the possible subarrays and find out the length of the minimum subarray whose sum is greater ...read more

CodingNinjas
author
2y
Sliding Window Approach

As all the elements in the ‘ARR’ are positive, if a subarray has a sum greater than ‘TARGET’ then adding other elements to the current subarray will make the sum even greater. T...read more

Add answer anonymously...
JPMorgan Chase & Co. Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter