Longest subarray having count of 1 s one more than count of 0 s | function to find the length of longest subarray having count of 1 ' s ▁ one ▁ more ▁ than ▁ count ▁ of ▁ 0' s ; unordered_map ' um ' implemented as hash table ; traverse the given array ; consider '0' as '-1   ; when subarray starts form index '0   ; make an entry for ' sum ' if it is not present in 'um   ; check if ' sum - 1' is present in ' um ' or not ; update maxLength ; required maximum length ; Driver code
def lenOfLongSubarr ( arr , n ) : NEW_LINE INDENT um = { i : 0 for i in range ( 10 ) } NEW_LINE sum = 0 NEW_LINE maxLen = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] == 0 : NEW_LINE INDENT sum += - 1 NEW_LINE DEDENT else : NEW_LINE INDENT sum += 1 NEW_LINE DEDENT if ( sum == 1 ) : NEW_LINE INDENT maxLen = i + 1 NEW_LINE DEDENT elif ( sum not in um ) : NEW_LINE INDENT um [ sum ] = i NEW_LINE DEDENT if ( ( sum - 1 ) in um ) : NEW_LINE INDENT if ( maxLen < ( i - um [ sum - 1 ] ) ) : NEW_LINE INDENT maxLen = i - um [ sum - 1 ] NEW_LINE DEDENT DEDENT DEDENT return maxLen NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 0 , 1 , 1 , 0 , 0 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Length ▁ = " , lenOfLongSubarr ( arr , n ) ) NEW_LINE DEDENT