AceYourInterviews
Checking sign-in…

147. Single Number

StarterFixed-width XOR cancellation under an exact multiplicity promise

Every distinct value except one appears exactly twice. Identify the remaining value, which occurs once, while preserving the array.

The occurrence promise is part of the problem; this is not a general most-frequent or least-frequent query. Signed integer values must retain their exact bit representation.

Example 1

Input

nums=[2,2,1]

Output

1

Explanation: The equal pair cancels, leaving the singleton.

Example 2

Input

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

Output

4

Explanation: Pairs need not be adjacent or sorted.

Example 3

Input

nums=[-2147483648,7,7]

Output

-2147483648

Explanation: The sign bit participates in XOR just like every other bit.

Constraints

  • 1 <= nums.length <= 100001
  • -231 <= nums[i] <= 231 - 1
  • The length is odd. Exactly one value occurs once; every other value occurs twice.
Hints
Hint 1

What binary operation makes a value cancel itself?

Hint 2

Can associativity and commutativity group nonadjacent equal occurrences conceptually?

Hint 3

Fold from zero with XOR, and explain why only the complete promised multiset has a singleton interpretation.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Nonadjacent pairs disappear only after all occurrences

[4,1,2,1,2]
4