150NeetCode 150

144.Single Number

EasyBit Manipulation ยท 1/7

Problem

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

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

Examples

Input:  nums = [2, 2, 1]
Output: 1
Explanation: 2 appears twice, 1 appears once.
Input:  nums = [4, 1, 2, 1, 2]
Output: 4
Explanation: 1 and 2 each appear twice; 4 is the only unpaired value.
Input:  nums = [1]
Output: 1

Constraints

  • 1 <= nums.length <= 3 * 10^4
  • -3 * 10^4 <= nums[i] <= 3 * 10^4
  • Each element appears twice except for one element which appears only once.

๐Ÿ’ก Key Insight

XOR has three properties that solve this instantly: x ^ x = 0, x ^ 0 = x, and it is commutative and associative, so order does not matter. XOR-ing the whole array makes every pair cancel to 0, leaving only the single number โ€” in one pass with one variable.

Brute Force

TimeO(nยฒ)SpaceO(1).

Intuition

For each element, count how many times it appears in the array. The one with count 1 is the answer.

Algorithm

  1. For each index i:
    • Count occurrences of nums[i] by scanning the whole array.
    • If the count is 1, return nums[i].
  2. (Unreachable for valid input) return -1.

Visualization

nums = [4, 1, 2, 1, 2]
nums[0] = 4 โ†’ appears 1 time โ†’ return 4

Code

java
class Solution {
    public int singleNumber(int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            int count = 0;
            for (int j = 0; j < nums.length; j++) {
                if (nums[j] == nums[i]) {
                    count++;
                }
            }
            if (count == 1) {
                return nums[i]; // the unpaired element
            }
        }
        return -1; // not reached for valid input
    }
}

Complexity

  • Time: O(nยฒ) โ€” a full scan for every element.
  • Space: O(1).

Complexity Comparison

Approach Time Space
Brute Force O(nยฒ) O(1)
Hash Set O(n) O(n)
XOR O(n) O(1)

Common Pitfalls

  • Starting the accumulator at something other than 0 โ€” 0 is XOR's identity; any other seed corrupts the result.
  • Worrying about negative numbers โ€” XOR works on the two's-complement bits, so negatives cancel just like positives.
  • Using a sum trick like 2 * sum(set) - sum(nums) โ€” correct, but it needs O(n) space and can overflow in other variants.
  • Applying the XOR trick to Single Number II (every other element appears three times) โ€” pairs no longer cancel; that variant needs per-bit counting mod 3.