Single Number I


136. Single Number – LeetCode


Problem Statement

Given a non-empty array of integers nums, every element appears twice except for one.
Find and return that single one.

You must implement a solution with linear runtime complexity and use only constant extra space.


Examples

Example 1:

Input: nums = [2,2,1]
Output: 1

Example 2:

Input: nums = [4,1,2,1,2]
Output: 4

Example 3:

Input: nums = [1]
Output: 1

Constraints


Intuition

XOR (^) is a powerful operation for this problem because:

By XORing all elements together, the pairs cancel out, and only the unique number remains.


Approach: XOR All Elements

  1. Initialize a variable xor = 0

  2. Traverse the array, XOR each element with xor

  3. After the loop, xor will hold the single number


Java Code

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

Time and Space Complexity

Metric Value
Time Complexity O(n)
Space Complexity O(1)
Explanation Single pass, no extra space used beyond a variable

Dry Run

Input: nums = [4, 1, 2, 1, 2]

Result: 4


Conclusion

This problem demonstrates an elegant use of bitwise XOR for eliminating duplicates. It's a classic example of: