Unique Element in an Array of Duplicates

Problem Every element in an array appears exactly twice except for one element, which appears exactly once. Find that single element.

Input / Output

  • Input: nums, an array of length n (n is odd) in which exactly one value occurs once and every other value occurs exactly twice.
  • Output: the value that appears only once.

Constraints

  • Target O(n) time and O(1) extra space, ruling out both hash-map counting and sorting.
  • Values may be negative and are not confined to any bounded range.
  • The array is unsorted and duplicate pairs are not necessarily adjacent.

Example

  • [4,1,2,1,2] → 4
  • [2,2,1] → 1
  • [-3,5,5] → -3 (negatives must work, which rules out a count-array indexed directly by value).
asked …
LeaderboardSalaryAccount