Algo-Sim › Matrix & Bit Manipulation

Single Number

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

Every number appears twice except one. XOR them all: pairs cancel to 0, leaving the single one, in O(1) space.

Problem

In the non-empty array nums, every value appears exactly twice except one, which appears once. Return that value, using linear time and constant extra space.

Constraints

Edge cases to test

Follow-up questions

What if the others appear three times?
Count each bit mod 3, or keep ones/twos bitmasks (LC 137): O(n), O(1).
What if two numbers appear once?
XOR everything to get a ^ b, split by its lowest set bit, and XOR each group (LC 260).

Solution

Java

public int singleNumber(int[] nums) {
    int x = 0;
    for (int num : nums) {
        x ^= num;
    }
    return x;
}

Python

def single_number(nums):
    x = 0
    for num in nums:
        x ^= num
    return x

C++

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

class Solution {
  public:
    int singleNumber(vector<int> &nums) {
        int x = 0;
        for (int num : nums) {
            x ^= num;
        }
        return x;
    }
};

More Matrix & Bit Manipulation problems