Single Number

25 min · singleNumber()

A badge scanner recorded every employee twice — except for one person who passed through only once. That lone record is the one you need.

Given an integer array nums, return the value that occurs once.

A few ground rules keep the signal clean:

  • One value appears exactly once.
  • Every other value appears exactly twice.
  • The array always has odd length, so the unpaired value is guaranteed to exist.

Constraints

  • 1 <= nums.length <= 100_000
  • nums.length is odd.
  • -30_000 <= nums[i] <= 30_000
  • Exactly one value appears once; every other value appears twice.

Hints

Count first

A map from value to frequency gives you a direct solution. What memory does it need when many different values appear?

Pairs should disappear

Exclusive OR (XOR) is a bitwise operation that keeps a bit when its two inputs differ. A value XORed with itself becomes zero, and zero XORed with a value returns that value.

Order doesn't matter

You can regroup and reorder XOR operations without changing the result. Fold the whole array, and every duplicate pair cancels, leaving only the unpaired value.

Follow-up

Can you find the answer in one pass while using the same amount of extra memory no matter how large the array becomes?

Visible cases

Examples

Example 1

ready
Input
nums = [
  2,
  2,
  1
]
Expected
1
Why
the pair of 2s cancels, leaving 1

Example 2

ready
Input
nums = [
  4,
  1,
  2,
  1,
  2
]
Expected
4
Why
1 and 2 each appear twice; 4 appears once

Example 3

ready
Input
nums = [
  7
]
Expected
7
Why
a one-element array is already unpaired

Interview signal

Asked at

AmazonGoogleMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite