Number of subarrays having sum exactly equal to k | Python3 program to find the number of subarrays with sum exactly equal to k . ; Function to find number of subarrays with sum exactly equal to k . ; Dictionary to store number of subarrays starting from index zero having particular value of sum . ; Sum of elements so far . ; Add current element to sum so far . ; If currsum is equal to desired sum , then a new subarray is found . So increase count of subarrays . ; currsum exceeds given sum by currsum - sum . Find number of subarrays having this sum and exclude those subarrays from currsum by increasing count by same amount . ; Add currsum value to count of different values of sum . ; Driver Code
from collections import defaultdict NEW_LINE def findSubarraySum ( arr , n , Sum ) : NEW_LINE INDENT prevSum = defaultdict ( lambda : 0 ) NEW_LINE res = 0 NEW_LINE currsum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT currsum += arr [ i ] NEW_LINE if currsum == Sum : NEW_LINE INDENT res += 1 NEW_LINE DEDENT if ( currsum - Sum ) in prevSum : NEW_LINE INDENT res += prevSum [ currsum - Sum ] NEW_LINE DEDENT prevSum [ currsum ] += 1 NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 2 , - 2 , - 20 , 10 ] NEW_LINE Sum = - 10 NEW_LINE n = len ( arr ) NEW_LINE print ( findSubarraySum ( arr , n , Sum ) ) NEW_LINE DEDENT