Find two unique numbers in an array with Python
Returns the two numbers that appear exactly once in a list where every other number appears twice, using XOR bit manipulation.
Python code
25 linesdef find_two_odd(arr):
"""Return the two numbers that appear exactly once, while all others appear twice."""
xor_all = 0
for num in arr:
xor_all ^= num
# xor_all now equals the XOR of the two unique numbers.
# Find a set bit (any bit where they differ).
diff_bit = xor_all & (-xor_all)
group1 = 0
group2 = 0
for num in arr:
if num & diff_bit:
group1 ^= num
else:
group2 ^= num
return group1, group2
if __name__ == "__main__":
arr = [4, 2, 4, 5, 2, 3, 3, 7]
result = find_two_odd(arr)
print(result)
Output
(5, 7)
How it works
The XOR of all numbers cancels out pairs, leaving the XOR of the two unique numbers. A set bit in this result indicates a position where the two numbers differ. Partitioning the array by that bit isolates each unique number in separate groups, and XORing each group yields the two numbers.
Common mistakes
- Forgetting that numbers can be negative, but diff_bit works with two's complement.
- Assuming the two unique numbers come out in sorted order.
- Using a set-based approach that runs in O(n) extra space instead of O(1).
Variations
- Return the numbers as a list sorted with sorted((group1, group2)) if order matters.
- Handle the edge case of an empty list by raising a ValueError before XOR.
Real-world use cases
- Finding duplicate-free IDs in a log stream where each legitimate event appears twice.
- Debugging data corruption to spot two corrupted records that broke a checksum.
- Analyzing network packet counters to detect two misconfigured nodes emitting unique values.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.