Count ways to split array into two equal sum subarrays by replacing each array element to 0 once | Function to find number of ways to split array into 2 subarrays having equal sum by changing element to 0 once ; Stores the count of elements in prefix and suffix of array elements ; Stores the sum of array ; Traverse the array ; Increase the frequency of current element in suffix ; Stores prefix sum upto index i ; Stores sum of suffix of index i ; Stores the desired result ; Traverse the array ; Modify prefix sum ; Add arr [ i ] to prefix map ; Calculate suffix sum by subtracting prefix sum from total sum of elements ; Remove arr [ i ] from suffix map ; Store the difference between the subarrays ; Count number of ways to split the array at index i such that subarray sums are equal ; Update the final result ; Return the result ; Driver Code ; Function Call
def countSubArrayRemove ( arr , N ) : NEW_LINE INDENT prefix_element_count = { } NEW_LINE suffix_element_count = { } NEW_LINE total_sum_of_elements = 0 NEW_LINE i = N - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT total_sum_of_elements += arr [ i ] NEW_LINE suffix_element_count [ arr [ i ] ] = suffix_element_count . get ( arr [ i ] , 0 ) + 1 NEW_LINE i -= 1 NEW_LINE DEDENT prefix_sum = 0 NEW_LINE suffix_sum = 0 NEW_LINE count_subarray_equal_sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT prefix_sum += arr [ i ] NEW_LINE prefix_element_count [ arr [ i ] ] = prefix_element_count . get ( arr [ i ] , 0 ) + 1 NEW_LINE suffix_sum = total_sum_of_elements - prefix_sum NEW_LINE suffix_element_count [ arr [ i ] ] = suffix_element_count . get ( arr [ i ] , 0 ) - 1 NEW_LINE difference = prefix_sum - suffix_sum NEW_LINE number_of_subarray_at_i_split = ( prefix_element_count . get ( difference , 0 ) + suffix_element_count . get ( - difference , 0 ) ) NEW_LINE count_subarray_equal_sum += number_of_subarray_at_i_split NEW_LINE DEDENT return count_subarray_equal_sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 1 , 1 , 3 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE print ( countSubArrayRemove ( arr , N ) ) NEW_LINE DEDENT