Single Number
Master this topic with zero to advance depth.
Single Number
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
Examples
Level I: Brute Force (Frequency Map)
Intuition
Count the frequency of each number using a hash map. The number with frequency 1 is the answer.
Level II: Sorting
Intuition
By sorting the array, identical elements become adjacent. We can then iterate through the array in steps of 2. If an element is not equal to its successor, it's the single number.
Level III: Optimal (XOR Manipulation)
Intuition
The XOR operator has two key properties: and . Since every number except one appears twice, XORing all elements together will cause the duplicates to cancel out, leaving only the single number.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.