← Back to Leo Academy Masterclass

Problem #136: Single Number

Easy Bit Manipulation

Intuition & Strategy Breakdown

Use bitwise XOR operation. XORing a number with itself yields 0, so XORing all elements together cancels duplicates and leaves the single number.

Python Solution

def singleNumber(nums):
    res = 0
    for n in nums:
        res ^= n
    return res

Java Solution

class Solution {
    public int singleNumber(int[] nums) {
        int res = 0;
        for (int n : nums) {
            res ^= n;
        }
        return res;
    }
}
Watch Interactive Video on Leo Academy Main App