Subarray Sums I
You are given an array of positive integers ‘ARR’ that represents the strengths of different “jutsus” (‘jutsu’ is a Japanese word for art i.e. ninja techniques) that a Ninja knows and can use to defeat enemies. You are also given the strength of the enemy ‘S’ (which is also a positive integer).
Your task is to count all the subarrays that have the combined strength as that of the given enemy and can help the Ninja to defeat the enemy.
A subarray is defined as a contiguous block of elements in the array.
Example:
Suppose given ‘ARR’ is [3, 1, 2, 4] and ‘S’ is 6 then
The count of the subarrays in ‘ARR’ that sum up to 6 is 2, i.e. subarrays ‘ARR[0...2]’ and ‘ARR[2...3]’.
Input Format
The first line of input contains a single integer ‘T’ denoting the number of test cases given. Then next ‘T’ lines follow:
The first line of each test case input contains two space-separated integers, where the first integer represents the length ‘ARR.length’ (‘N’) of the elements which would be given in the ‘ARR’ array/list while the second integer is the value ‘S’.
The next line of each test, contains ‘N’ space-separated integers which are the elements of the ‘ARR’ array.
Output Format:
For every test case, return the count of all subarrays that sum up to the given strength ‘S’ of the enemy.
Output for each test case should be in a separate line.
Note:
You do not need to print anything; it has already been taken care of. Just Implement the given function.
Constraint :
1 <= ‘T’ <= 100
1 <= ‘N’<= 10^3
1 <= ‘ARR’[i] <= 10^9
1 <= ‘S’ <= 10^9
Where ‘ARR[i]' is the 'i_th' element of array 'ARR'.
Time Limit: 1 sec
CodingNinjas
author
2y
Brute Force
A simple solution could be to traverse all the subarrays and calculate their sum. If the sum is equal to the given required sum, then, increment the count of subarrays. Finally return the c...read more
CodingNinjas
author
2y
Hashing
An efficient solution is while traversing the array, we keep storing the sum that we have gotten so far in ‘CURRSUM’. Here would also need to maintain the count of different values of ‘CURRSUM’...read more
Help your peers!
Add answer anonymously...
Top SAP Software Developer Intern interview questions & answers
Popular interview questions of Software Developer Intern
Stay ahead in your career. Get AmbitionBox app
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