Unique element in an array where all elements occur K times except one | Set 2 | Function to find single occurrence element ; By shifting 1 to left ith time and taking and with 1 will give us that ith bit of a [ j ] is 1 or 0 ; Taking modulo of p with k ; Generate result ; Loop for negative numbers ; Check if the calculated value res is present in array , then mark c = 1 and if c = 1 return res else res must be - ve ; Driver code ; Function call
def findunique ( a , k ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( 32 ) : NEW_LINE INDENT p = 0 NEW_LINE for j in range ( len ( a ) ) : NEW_LINE INDENT if ( abs ( a [ j ] ) & ( 1 << i ) ) != 0 : NEW_LINE INDENT p += 1 NEW_LINE DEDENT DEDENT p %= k NEW_LINE res += pow ( 2 , i ) * p NEW_LINE DEDENT c = 0 NEW_LINE for x in a : NEW_LINE INDENT if ( x == res ) : NEW_LINE INDENT c = 1 NEW_LINE break NEW_LINE DEDENT DEDENT if c == 1 : NEW_LINE INDENT return res NEW_LINE DEDENT else : NEW_LINE INDENT return - res NEW_LINE DEDENT DEDENT a = [ 12 , 12 , 2 , 2 , 3 ] NEW_LINE k = 2 NEW_LINE print ( findunique ( a , k ) ) NEW_LINE