Complete the code to find the XOR of all elements in the array.
def find_xor(arr): result = 0 for num in arr: result = result [1] num return result arr = [2, 3, 7, 9, 2, 3, 9, 11] print(find_xor(arr))
The XOR operator ^ is used to find the XOR of two numbers. Here, we XOR all elements to get the XOR of the two unique numbers.
Complete the code to find the rightmost set bit in the XOR result.
def rightmost_set_bit(xor_result): return xor_result & -[1] xor_result = 12 print(rightmost_set_bit(xor_result))
The expression xor_result & -xor_result isolates the rightmost set bit of xor_result.
Fix the error in the code to correctly separate the two unique numbers using the set bit.
def find_two_unique(arr): xor_all = 0 for num in arr: xor_all ^= num set_bit = xor_all & -xor_all num1 = 0 num2 = 0 for num in arr: if num & [1]: num1 ^= num else: num2 ^= num return num1, num2 arr = [4, 1, 2, 1, 2, 5] print(find_two_unique(arr))
The variable set_bit holds the rightmost set bit used to separate the two unique numbers.
Fill both blanks to complete the function that returns the two unique numbers in sorted order.
def find_two_unique_sorted(arr): xor_all = 0 for num in arr: xor_all ^= num set_bit = xor_all & -xor_all num1 = 0 num2 = 0 for num in arr: if num & [1]: num1 ^= num else: num2 ^= num return tuple(sorted(([2], num2))) arr = [10, 20, 10, 30] print(find_two_unique_sorted(arr))
The first blank should be set_bit to separate groups. The second blank should be num1 to return the first unique number.
Fill all three blanks to complete the function that finds two unique numbers using XOR and returns them sorted.
def two_non_repeating(arr): xor_all = 0 for num in arr: xor_all ^= num set_bit = xor_all & -[1] num1 = 0 num2 = 0 for num in arr: if num & [2]: num1 ^= num else: num2 ^= num return tuple(sorted((num1, [3]))) arr = [1, 2, 3, 2, 1, 4] print(two_non_repeating(arr))
The first blank is xor_all to get the negative for isolating the rightmost set bit. The second blank is set_bit to separate groups. The third blank is num2 to return the second unique number.