Subarrays with sum K

Medium Accuracy: 65.67% Submissions: 5548 Points: 4


Given an unsorted array of integers, find the number of continuous subarrays having sum exactly equal to a given number k.


Example 1:

Input:
N = 5
Arr = {10 , 2, -2, -20, 10}
k = -10
Output: 3
Explaination: 
Subarrays: arr[0...3], arr[1...4], arr[3..4]
have sum exactly equal to -10.


Example 2:

Input:
N = 6
Arr = {9, 4, 20, 3, 10, 5}
k = 33
Output: 2
Explaination: 
Subarrays : arr[0...2], arr[2...4] have sum
exactly equal to 33.


Your Task:
You don't need to read input or print anything. Your task is to complete the function findSubArraySum() which takes the array Arr[] and its size and as input parameters and returns the count of subarrays.



from collections import defaultdict


class Solution:

    def findSubArraySum(self, Arr, n, k):

        # code here

        d = defaultdict(lambda :0)

        res = 0

        c = 0

        for i in Arr:

            c +=i

            #print(c,'csum')

            #print(c-k,'prevsum')

            if(c==k):

                res+=1

            if c-k in d:

                res+=d[c-k]

            d[c]+=1

            #print(res,'res')

        return res

                


Comments

Popular posts from this blog

Large Factorial of array

Value equal to index value

Largest Element in Array