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";
  • Gaurav Dhimate

    Java 8 version for XOR method.

    public static int singleNumber8(int[] elements)
    return Arrays.stream(elements).reduce(0,(a, b) -> a ^ b);

  • Milos Kosanovic

    public int singleNumber(int[] A){
    List list=Arrays.stream(A).boxed().collect(Collectors.toList());
    int number=0;
    for(int i=0;i<A.length;i++){
    if(Collections.frequency(list, A[i])==1){
    return number;

  • kkkkbbbb

    no extra space dude

  • 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.