Count subarrays with same even and odd elements | function that returns the count of subarrays that contain equal number of odd as well as even numbers ; initialize difference and answer with 0 ; initialize these auxiliary arrays with 0 ; since the difference is initially 0 , we have to initialize hash_positive [ 0 ] with 1 ; for loop to iterate through whole array ( zero - based indexing is used ) ; incrementing or decrementing difference based on arr [ i ] being even or odd , check if arr [ i ] is odd ; adding hash value of ' difference ' to our answer as all the previous occurrences of the same difference value will make even - odd subarray ending at index ' i ' . After that , we will increment hash array for that ' difference ' value for its occurrence at index ' i ' . if difference is negative then use hash_negative ; else use hash_positive ; return total number of even - odd subarrays ; Driver code ; Printing total number of even - odd subarrays
def countSubarrays ( arr , n ) : NEW_LINE INDENT difference = 0 NEW_LINE ans = 0 NEW_LINE hash_positive = [ 0 ] * ( n + 1 ) NEW_LINE hash_negative = [ 0 ] * ( n + 1 ) NEW_LINE hash_positive [ 0 ] = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] & 1 == 1 ) : NEW_LINE INDENT difference = difference + 1 NEW_LINE DEDENT else : NEW_LINE INDENT difference = difference - 1 NEW_LINE DEDENT if ( difference < 0 ) : NEW_LINE INDENT ans += hash_negative [ - difference ] NEW_LINE hash_negative [ - difference ] = hash_negative [ - difference ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans += hash_positive [ difference ] NEW_LINE hash_positive [ difference ] = hash_positive [ difference ] + 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 3 , 4 , 6 , 8 , 1 , 10 , 5 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Total ▁ Number ▁ of ▁ Even - Odd ▁ subarrays ▁ are ▁ " + str ( countSubarrays ( arr , n ) ) ) NEW_LINE