Single Number in Java Using XOR

This guide explains the intuition, optimized approach, and Java implementation for single number in java using xor, with practical tips for interviews and production coding standards.

Problem

Every element appears twice except one. Find that one.

Why XOR Works

  • a ^ a = 0
  • a ^ 0 = a
  • XOR is commutative and associative

Pair values cancel out, unique value remains.

Java Solution

class Solution {
    public int singleNumber(int[] nums) {
        int result = 0;
        for (int n : nums) {
            result ^= n;
        }
        return result;
    }
}

Complexity

  • Time: O(n)
  • Space: O(1)

Key Takeaways

  • Start from the brute-force idea, then derive the optimized invariant.
  • Use clean pointer/index boundaries to avoid off-by-one bugs.
  • Validate against edge cases (empty input, single element, duplicates, extreme values).