Count of Substrings having Sum equal to their Length | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubstrings ( string s , int n ) { int count = 0 , sum = 0 ; unordered_map < int , int > mp ; mp [ 0 ] ++ ; for ( int i = 0 ; i < n ; ++ i ) { sum += ( s [ i ] - '0' ) ; count += mp [ sum - ( i + 1 ) ] ; ++ mp [ sum - ( i + 1 ) ] ; } return count ; } int main ( ) { string str = "112112" ; int n = str . length ( ) ; cout << countSubstrings ( str , n ) << endl ; return 0 ; }