|
| 1 | +def find_two_unique_numbers(arr: list[int]) -> tuple[int,int]: |
| 2 | + """ |
| 3 | + Given a list of integers where every elemnt appears twice except for two numbers, |
| 4 | + find the two numbers that appear only once. |
| 5 | +
|
| 6 | + this method returns the tuple of two numbers that appear only once using bitwise XOR |
| 7 | + and using the property of x & -x to isolate the rightmost bit |
| 8 | + (different bit between the two unique numbers). |
| 9 | +
|
| 10 | + >>> find_two_unique_numbers([1,2,3,4,1,2]) |
| 11 | + (3, 4) |
| 12 | +
|
| 13 | + >>> find_two_unique_numbers([4,5,6,7,4,5]) |
| 14 | + (6, 7) |
| 15 | +
|
| 16 | + >>> find_two_unique_numbers([10,20,30,10,20,40]) |
| 17 | + (30, 40) |
| 18 | +
|
| 19 | + >>> find_two_unique_numbers([2,3]) |
| 20 | + (2, 3) |
| 21 | +
|
| 22 | + >>> find_two_unique_numbers([]) |
| 23 | + Traceback (most recent call last): |
| 24 | + ... |
| 25 | + ValueError: input list must not be empty |
| 26 | + >>> find_two_unique_numbers([1, 'a', 1]) |
| 27 | + Traceback (most recent call last): |
| 28 | + ... |
| 29 | + TypeError: all elements must be integers |
| 30 | + """ |
| 31 | + |
| 32 | + if not arr: |
| 33 | + raise ValueError("input list must not be empty") |
| 34 | + if not all(isinstance(x,int) for x in arr): |
| 35 | + raise TypeError("all elements must be integers") |
| 36 | + |
| 37 | + xor_result = 0 |
| 38 | + for number in arr: |
| 39 | + xor_result^=number |
| 40 | + |
| 41 | + righmost_bit=xor_result & -xor_result |
| 42 | + |
| 43 | + num1=0 |
| 44 | + num2=0 |
| 45 | + |
| 46 | + for number in arr: |
| 47 | + if number & righmost_bit: |
| 48 | + num1^=number |
| 49 | + else: |
| 50 | + num2^=number |
| 51 | + return tuple(sorted((num1,num2))) |
| 52 | + |
| 53 | +if __name__=="__main__": |
| 54 | + import doctest |
| 55 | + |
| 56 | + doctest.testmod() |
0 commit comments