Single Number

Difficulty: Easy

Every number in a list appears exactly twice, except one that appears once. Find that number.

Use a single pass and no extra data structures that grow with the input.

Examples

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

2 appears twice; 1 appears only once.

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

1 and 2 each appear twice; 4 appears only once.

Input: nums = [1]
Output: 1

Constraints

  • 1 <= nums.length <= 3 * 10^4

  • -3 * 10^4 <= nums[i] <= 3 * 10^4

  • Every element appears twice, except for exactly one which appears once.

Approach

The direct way is to count each number with a hash map and return the one with count 1. That needs extra memory for every distinct value.

XOR (bitwise exclusive-or, the ^ operator) needs no extra memory. Bit by bit, XORing two equal bits gives 0, and XORing with 0 changes nothing. So any number XORed with itself is 0, and any number XORed with 0 is itself.

XOR every number into one running total. Each pair of equal values cancels to 0, in any order. Only the number without a partner is left.

Solutions

Brute Force - Count With a Hash Map

Count how many times each number appears using a hash map, then return the one whose count is exactly 1.

function singleNumber(nums) {
  const counts = new Map();

  for (const num of nums) {
    counts.set(num, (counts.get(num) || 0) + 1);
  }

  for (const [num, count] of counts.entries()) {
    if (count === 1) return num;
  }
}

Time: O(n) · Space: O(n)

Optimal - XOR Everything Together

XOR every number into a running result that starts at 0. Each pair of equal values cancels to 0 (in any order), so what's left is the number that appeared once.

function singleNumber(nums) {
  let result = 0;

  for (const num of nums) {
    result ^= num;
  }

  return result;
}

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