Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: 20 Apr, 2021

Count All Subarrays With Given Sum

Moderate
Asked in companies
SAP LabsCognizantCurefit

Problem statement

You are given an integer array 'arr' of size 'N' and an integer 'K'.

Your task is to find the total number of subarrays of the given array whose sum of elements is equal to k.

A subarray is defined as a contiguous block of elements in the array.

Example:
Input: ‘N’ = 4, ‘arr’ = [3, 1, 2, 4], 'K' = 6

Output: 2

Explanation: The subarrays that sum up to '6' are: [3, 1, 2], and [2, 4].
Input Format
The first input line contains a single integer ‘T’, denoting the number of test cases.

For each Test case:

The first line of each test case input contains two space-separated integers, where the first integer represents the length of the array 'N', and the second integer is the value ‘K’.

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 integer 'K'.
Note:
You do not need to print anything; it has already been taken care of. Just Implement the given function.
Constraint :
1 <= T <= 10
1 <= N<= 10^3
1 <= arr[i] <= 10^9
1 <= K <= 10^9

Time Limit: 1 sec

Approaches

01 Approach

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 count of such subarrays. 

 

The steps are as follows:-
 

// Function to find the number of subarrays with sum ‘k’

function findAllSubarraysWithGivenSum(int[] arr, int k):

  1. Int ‘n’ be the size of the array ‘arr’.
  2. Initialize a variable ‘res’ initially assigned to ‘0’, which will store the number of subarrays with sum ‘k’.
  3. Iterate from index ‘1’ to index ‘n’ using variable ‘i’:
    • Initialize a variable ‘currSum’ initially assigned to ‘0’, which will store the sum of the current subarray.
    • Iterate from index ‘i’ to index ‘n’ using variable ‘j’:
      • Add arr[j] to ‘currSum’.
      • If ‘currSum == k’:
        • Increment ‘res’ by 1.
      • Else if ‘currSum > k’:
        • Break
  4. Return ‘res’.