Leetcode – Single Number (Java)

The problem:

Given an array of integers, every element appears twice except for one. Find that single one.

Java Solution 1

The key to solve this problem is bit manipulation. XOR will return 1 only on two different bits. So if two numbers are the same, XOR will return 0. Finally only one number left.

public int singleNumber(int[] A) {
	int x = 0;
	for (int a : A) {
		x = x ^ a;
	return x;

Java Solution 2

public int singleNumber(int[] A) {
	HashSet<Integer> set = new HashSet<Integer>();
	for (int n : A) {
		if (!set.add(n))
	Iterator<Integer> it = set.iterator();
	return it.next();

The question now is do you know any other ways to do this?

Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";
  • Vipin Tiwari

    it.hasNext will return the boolean value and method signature is having int as output

  • fishwen

    XOR is associative: x ^ (y ^ z) == (x ^ y) ^ z

  • Adil qureshi

    u r rite .. 🙂

  • Peter

    ‘Every element appears twice except for one’

  • Adil qureshi

    Have you unit tested it … this does not work …for eg int arr[] = {12, 1, 12, 3, 12, 1, 1, 2, 3, 3}; output should be 2 …

  • Frank

    This is wat I came up with:

    public static int singleNumber(int[] numbers)
    if(numbers == null)
    throw new NullPointerException(“Parameter numbers cannot be null.”);
    if(numbers.length == 0)
    throw new IllegalArgumentException(“Parameter numbers cannot be empty.”);

    Set oddNumbers = new HashSet();
    for(int i=0; i<numbers.length; i++) {
    int number = numbers[i];

    if(oddNumbers.size() != 1)
    throw new IllegalArgumentException("Parameter number does not contain a single number.");

    return oddNumbers.iterator().next();

  • raman singh

    nice solution . better than using map like I did.

  • nirvana_tan


  • 象道

    a linear but not so fast alg: using hash table.