Single Number III

Pattern: XOR tricks

medium

XOR everything to get a ^ b for the two singles. Any set bit of that result is a bit where a and b differ. Split all values by that bit and XOR each group; each group holds one single plus whole pairs.

The problem

In an array, exactly two values appear once and every other value appears exactly twice. Return the two single values, in O(n) time and O(1) extra memory. For example, [1, 2, 1, 3, 2, 5] gives [3, 5].

The function name singleNumber matches LeetCode. Use the link above for the exact statement and limits. LeetCode accepts either order; this guide returns the smaller value first.

Think first

  • What does XOR-ing everything give you now?
  • If you could split the array into two groups, each holding one single, what would you do?
  • Which bit separates the two singles?

Hints

    Brute force, and why it fails

    A hash map of counts: O(n) memory. Sorting: O(n log n). The split trick: O(n) time, O(1) memory.

    The key insight

    One differing bit is enough to separate the two singles, and splitting by it keeps every pair together, so each half becomes the one-single problem.

    Dry run

    xor6

    nums = [1, 2, 1, 3, 2, 5]. XOR of everything is 3 ^ 5 = 6 (binary 110).

    Step 1 of 4

    The plan

    x = XOR of all nums
    low = x & -x
    a = XOR of nums with (v & low) != 0
    b = XOR of nums with (v & low) == 0
    return [min(a, b), max(a, b)]
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    Two passes.

    Edge cases

    • Only the two singles: [-1, 0] gives [-1, 0].
    • The singles are the smallest and largest ints: low may be the sign bit; it still splits correctly.
    • Negative values: their bits split the same way.
    I've built my logic, show the code

    Java

    class Solution {
        public int[] singleNumber(int[] nums) {
            int xor = 0;
            for (int v : nums) xor ^= v;            // = a ^ b, the two singles
            int low = xor & -xor;                   // a bit where a and b differ (the lowest set bit)
            int a = 0, b = 0;
            for (int v : nums) {
                if ((v & low) != 0) a ^= v;         // split everything by that bit: a and b fall in different groups
                else b ^= v;
            }
            return a < b ? new int[]{a, b} : new int[]{b, a};   // smaller first
        }
    }

    C++

    class Solution {
    public:
        vector<int> singleNumber(vector<int>& nums) {
            unsigned int x = 0;
            for (int v : nums) x ^= static_cast<unsigned int>(v);   // = a ^ b, the two singles
            unsigned int low = x & (~x + 1u);       // a bit where a and b differ (the lowest set bit)
            int a = 0, b = 0;
            for (int v : nums) {
                if (static_cast<unsigned int>(v) & low) a ^= v;   // split by that bit: a and b fall in different groups
                else b ^= v;
            }
            if (a > b) swap(a, b);                  // smaller first
            return {a, b};
        }
    };

    Python

    class Solution:
        def singleNumber(self, nums: list[int]) -> list[int]:
            xor = 0
            for v in nums:
                xor ^= v                            # = a ^ b, the two singles
            low = xor & -xor                        # a bit where a and b differ (the lowest set bit)
            a = b = 0
            for v in nums:
                if v & low:                         # split everything by that bit: a and b fall in different groups
                    a ^= v
                else:
                    b ^= v
            return sorted([a, b])                   # smaller first

    Common mistakes

    • Computing x & -x in C++ with a signed x equal to -2³¹, which overflows; use unsigned.
    • Splitting by v & low == 0 without brackets in Java or C++.
    • Returning the singles in an unspecified order when one order is required.

    Similar problems