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.

Medium Python 3.9+ Aug 9, 2026 Algorithms & data structures 13 views 0 copies

Python code

25 lines
Python 3.9+
def 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

stdout
(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

  1. Return the numbers as a list sorted with sorted((group1, group2)) if order matters.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.