InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Bit Manipulation

Single Number

easy Original ↗ 00:00

Problem

You are given a non-empty array nums in which every element appears exactly twice except for one element, which appears exactly once. Return that single element. You must do it in linear time using only constant extra space.

Examples

  • [2, 2, 1]1. The two 2s pair up; 1 is unpaired.
  • [4, 1, 2, 1, 2]4. The 1s and 2s each pair up; 4 is unpaired.
  • [7]7. A single element with no pair.

Constraints

  • 1 <= len(nums) <= 3 * 10^4
  • -3 * 10^4 <= nums[i] <= 3 * 10^4
  • Every element appears twice except one, which appears once.

Required: O(n) time and O(1) extra space.

Think about it first

Hint 1 A hash map of counts, or a set you toggle membership in, finds the unpaired element, but both use O(n) extra space, which the problem forbids.
Hint 2 XOR has two useful properties: `x ^ x = 0` (a value cancels itself) and `x ^ 0 = x` (zero is the identity). XOR is also order-independent.
Hint 3 XOR every element of the array together. Each paired value cancels to `0`, and the unpaired value XORed with `0` is itself. The running XOR is the answer, computed in one pass with a single variable.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug