Single Number III

medium array bit manipulation

Problem

You are given an integer array nums in which exactly two elements appear once and every other element appears twice. Return the two single elements in any order, in O(n) time and O(1) space.

XOR everything: pairs cancel, leaving xorAll = a ^ b. Any bit set in xorAll is a position where a and b differ — isolate the lowest such bit with xorAll & -xorAll. Partition nums on that bit and XOR each half independently — each half now contains pairs plus one of the singletons.

Inputnums = [1, 2, 1, 3, 2, 5]
Output[3, 5]

def single_number(nums):
    xor_all = 0
    for x in nums:
        xor_all ^= x
    diff = xor_all & -xor_all
    a, b = 0, 0
    for x in nums:
        if x & diff:
            a ^= x
        else:
            b ^= x
    return [a, b]
function singleNumber(nums) {
  let xorAll = 0;
  for (const x of nums) xorAll ^= x;
  const diff = xorAll & -xorAll;
  let a = 0, b = 0;
  for (const x of nums) {
    if (x & diff) a ^= x;
    else b ^= x;
  }
  return [a, b];
}
class Solution {
    public int[] singleNumber(int[] nums) {
        int xorAll = 0;
        for (int x : nums) xorAll ^= x;
        int diff = xorAll & -xorAll;
        int a = 0, b = 0;
        for (int x : nums) {
            if ((x & diff) != 0) a ^= x;
            else b ^= x;
        }
        return new int[]{ a, b };
    }
}
vector<int> singleNumber(vector<int>& nums) {
    int xorAll = 0;
    for (int x : nums) xorAll ^= x;
    int diff = xorAll & -xorAll;
    int a = 0, b = 0;
    for (int x : nums) {
        if (x & diff) a ^= x;
        else b ^= x;
    }
    return {a, b};
}
Time: O(n) Space: O(1)