Count of Substrings having Sum equal to their Length | Python3 program to implement the above approach ; Function to count the number of substrings with sum equal to length ; Stores the count of substrings ; Add character to sum ; Add count of substrings to result ; Increase count of subarrays ; Return count ; Driver code
from collections import defaultdict NEW_LINE def countSubstrings ( s , n ) : NEW_LINE INDENT count , sum = 0 , 0 NEW_LINE mp = defaultdict ( lambda : 0 ) NEW_LINE mp [ 0 ] += 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += ord ( s [ i ] ) - ord ( '0' ) NEW_LINE count += mp [ sum - ( i + 1 ) ] NEW_LINE mp [ sum - ( i + 1 ) ] += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT str = '112112' NEW_LINE n = len ( str ) NEW_LINE print ( countSubstrings ( str , n ) ) NEW_LINE