Count subarrays having an equal count of 0 s and 1 s segregated | Function to count subarrays having equal count of 0 s and 1 s with all 0 s and all 1 s grouped together ; Stores the count of subarrays ; If current element is different from the next array element ; Increment count ; Count the frequency of 1 s and 0 s ; Increment count ; Print the final count ; Driver Code ; Function Call
def countSubarrays ( A , N ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT if ( A [ i ] != A [ i + 1 ] ) : NEW_LINE INDENT ans += 1 ; NEW_LINE j = i - 1 ; k = i + 2 ; NEW_LINE while ( j >= 0 and k < N and A [ j ] == A [ i ] and A [ k ] == A [ i + 1 ] ) : NEW_LINE INDENT ans += 1 ; NEW_LINE j -= 1 ; NEW_LINE k += 1 ; NEW_LINE DEDENT DEDENT DEDENT print ( ans ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 1 , 1 , 0 , 0 , 1 , 0 ] ; NEW_LINE N = len ( A ) ; NEW_LINE countSubarrays ( A , N ) ; NEW_LINE DEDENT