← Bit Manipulation

Single Number XOR

Easy
Python
def single_number(nums):
    r=0
    for n in nums: r^=n
    return r
Java
public int singleNumber(int[] nums){
    int r=0;
    for(int n:nums) r^=n;
    return r;
}

Key Insight

Most identical Python-Java solution.

Python → Java Differences

  • XOR identical
  • Most similar solution
  • Java needs int declaration
Python
def single_number(nums):
    r=0
    for n in nums: r^=n
    return r
Java
public int singleNumber(int[] nums){
    int r=0;
    for(int n:nums) r^=n;
    return r;
}

Algorithm Steps

1. XOR all
2. Duplicates cancel