Algo-Sim › Matrix & Bit Manipulation

Single Number III

Medium · Matrix & Bit Manipulation · step through it in Java, Python and C++ on your own input

Two numbers appear once, the rest twice. XOR all gives a ^ b; its lowest set bit splits the array into two groups, each XORing to one single.

Problem

In the array nums, exactly two values appear once and every other value appears exactly twice. Return the two single values, in any order, using linear time and constant extra space.

Constraints

Edge cases to test

Follow-up questions

Why does the lowest set bit split them?
a ^ b has a 1 where a and b differ; any such bit puts them in different groups, while each pair lands together.
Is x & −x safe in Java and C++?
For Integer.MIN_VALUE it overflows to itself, which is still its lowest bit. In C++ use unsigned or long long to avoid undefined behaviour.

Solution

Java

public int[] singleNumber(int[] nums) {
    int xor = 0;
    for (int num : nums) xor ^= num;
    // a ^ b != 0, so a and b differ at its lowest set bit.
    int low = xor & -xor;
    int[] out = new int[2];
    for (int num : nums) {
        if ((num & low) != 0) out[0] ^= num;
        else out[1] ^= num;
    }
    return out;
}

Python

def single_number(nums):
    xor = 0
    for num in nums:
        xor ^= num
    # a ^ b != 0, so a and b differ at its lowest set bit.
    low = xor & -xor
    out = [0, 0]
    for num in nums:
        if num & low:
            out[0] ^= num
        else:
            out[1] ^= num
    return out

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<int> singleNumber(vector<int> &nums) {
        unsigned x = 0;
        for (int num : nums) x ^= num;
        // a ^ b != 0, so a and b differ at its lowest set bit.
        unsigned low = x & -x;
        vector<int> out(2);
        for (int num : nums) {
            if (num & low) out[0] ^= num;
            else out[1] ^= num;
        }
        return out;
    }
};

More Matrix & Bit Manipulation problems