Find the two repeating elements in a given array | Python3 code to Find the two repeating elements in a given array ; Will hold xor of all elements ; Will have only single set bit of xor ; Get the xor of all elements in arr [ ] and 1 , 2 . . n ; Get the rightmost set bit in set_bit_no ; Now divide elements in two sets by comparing rightmost set bit of xor with bit at same position in each element . ; XOR of first set in arr [ ] ; XOR of second set in arr [ ] ; XOR of first set in arr [ ] and 1 , 2 , ... n ; XOR of second set in arr [ ] and 1 , 2 , ... n ; Driver code
def printRepeating ( arr , size ) : NEW_LINE INDENT xor = arr [ 0 ] NEW_LINE n = size - 2 NEW_LINE x = 0 NEW_LINE y = 0 NEW_LINE for i in range ( 1 , size ) : NEW_LINE INDENT xor ^= arr [ i ] NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT xor ^= i NEW_LINE DEDENT set_bit_no = xor & ~ ( xor - 1 ) NEW_LINE for i in range ( 0 , size ) : NEW_LINE INDENT if ( arr [ i ] & set_bit_no ) : NEW_LINE INDENT x = x ^ arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT y = y ^ arr [ i ] NEW_LINE DEDENT DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( i & set_bit_no ) : NEW_LINE INDENT x = x ^ i NEW_LINE DEDENT else : NEW_LINE INDENT y = y ^ i NEW_LINE DEDENT DEDENT print ( " The ▁ two ▁ repeating " , " elements ▁ are " , y , x ) NEW_LINE DEDENT arr = [ 4 , 2 , 4 , 5 , 2 , 3 , 1 ] NEW_LINE arr_size = len ( arr ) NEW_LINE printRepeating ( arr , arr_size ) NEW_LINE