Author
Result
0.2507 s
Code
def find_two_missing(numbers: list[int], n: int) -> set[int]:
"""
Finds two missing numbers from a list of integers from 0 to n-1 using Bit Manipulation.
1. XOR all numbers from 0 to n-1.
2. XOR all numbers present in the input list.
3. The result is x ^ y.
4. Find a set bit in x ^ y.
5. Partition the numbers into two groups based on this bit.
6. XOR the groups to find x and y.
"""
xor_all = 0
# XOR all numbers from 0 to n-1
for i in range(n):
xor_all ^= i
# XOR with numbers present in the list
for num in numbers:
xor_all ^= num
# At this point, xor_all = x ^ y
# Find the rightmost set bit (a differing bit between x and y)
# Using x & -x to isolate the lowest set bit
set_bit = xor_all & -xor_all
missing_a = 0
missing_b = 0
# Iterate through the range and list to partition
for i in range(n):
if i & set_bit:
missing_a ^= i
else:
missing_b ^= i
for num in numbers:
if num & set_bit:
missing_a ^= num
else:
missing_b ^= num
return {missing_a, missing_b}