2dbi

Find the single non-duplicate number in an array

via2dbi

Problem

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

Example

[4, 1, 2, 1, 2] -> 4

Constraints

  • Every element appears twice except one
  • Aim for O(n) time and O(1) space

Approach

XOR all elements: equal pairs cancel to 0, leaving the unique value.

Add a follow-up question they asked
Single Number II: every other element appears three times.
Single element in a sorted array (LeetCode 540).
asked …
LeaderboardSalary
Language
Account