1- #Reference : https://www.geeksforgeeks.org/dsa/find-two-non-repeating-elements-in-an-array-of-repeating-elements
2- def find_two_unique_numbers (arr : list [int ]) -> tuple [int ,int ]:
1+ # Reference : https://www.geeksforgeeks.org/dsa/find-two-non-repeating-elements-in-an-array-of-repeating-elements
2+ def find_two_unique_numbers (arr : list [int ]) -> tuple [int , int ]:
33 """
44 Given a list of integers where every elemnt appears twice except for two numbers,
55 find the two numbers that appear only once.
66
77 this method returns the tuple of two numbers that appear only once using bitwise XOR
8- and using the property of x & -x to isolate the rightmost bit
8+ and using the property of x & -x to isolate the rightmost bit
99 (different bit between the two unique numbers).
1010
1111 >>> find_two_unique_numbers([1,2,3,4,1,2])
@@ -32,26 +32,27 @@ def find_two_unique_numbers(arr: list[int]) -> tuple[int,int]:
3232
3333 if not arr :
3434 raise ValueError ("input list must not be empty" )
35- if not all (isinstance (x ,int ) for x in arr ):
35+ if not all (isinstance (x , int ) for x in arr ):
3636 raise TypeError ("all elements must be integers" )
37-
37+
3838 xor_result = 0
3939 for number in arr :
40- xor_result ^= number
40+ xor_result ^= number
4141
42- righmost_bit = xor_result & - xor_result
42+ righmost_bit = xor_result & - xor_result
4343
44- num1 = 0
45- num2 = 0
44+ num1 = 0
45+ num2 = 0
4646
4747 for number in arr :
4848 if number & righmost_bit :
49- num1 ^= number
49+ num1 ^= number
5050 else :
51- num2 ^= number
52- return tuple (sorted ((num1 ,num2 )))
51+ num2 ^= number
52+ return tuple (sorted ((num1 , num2 )))
53+
5354
54- if __name__ == "__main__" :
55+ if __name__ == "__main__" :
5556 import doctest
5657
5758 doctest .testmod ()
0 commit comments