Single Number - Problem

Imagine you have a collection of items where every item appears exactly twice, except for one special item that appears only once. Your mission is to find that single unique item efficiently!

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

Challenge: You must implement a solution with linear runtime complexity O(n) and use only constant extra space O(1).

Example: In the array [2, 2, 1], the number 1 appears only once while 2 appears twice. So the answer is 1.

Input & Output

example_1.py โ€” Basic Case
$ Input: [2, 2, 1]
โ€บ Output: 1
๐Ÿ’ก Note: The number 1 appears once while 2 appears twice, so the single number is 1.
example_2.py โ€” Larger Array
$ Input: [4, 1, 2, 1, 2]
โ€บ Output: 4
๐Ÿ’ก Note: Numbers 1 and 2 each appear twice, while 4 appears only once, making 4 the single number.
example_3.py โ€” Single Element
$ Input: [1]
โ€บ Output: 1
๐Ÿ’ก Note: The array contains only one element, so that element is the single number.

Visualization

Tap to expand
๐ŸŽญ The XOR Magic Show: Finding the Single Number๐ŸŽช Magic Stage2First 2 appears2Second 2 - POOF!โœจ Twins Cancel Out! โœจ1๐ŸŒŸ The Survivor! ๐ŸŒŸ๐Ÿ”ฎ The XOR Spell2 โŠ• 2 โŠ• 1 = 0 โŠ• 1 = 1Identical numbers vanish, single number remainsTime: O(n) | Space: O(1) | Pure Magic! โœจ
Understanding the Visualization
1
Start the Magic Show
Begin with an empty stage (result = 0)
2
First Twin Appears
The first occurrence of each number steps onto the stage
3
Twin Reunion
When the second occurrence meets its twin, both vanish with XOR magic!
4
The Lone Survivor
Only the single number remains on stage - our answer!
Key Takeaway
๐ŸŽฏ Key Insight: XOR is the perfect tool for this problem because it naturally cancels out pairs (aโŠ•a=0) while preserving single elements (aโŠ•0=a), giving us an elegant O(n) time, O(1) space solution!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through the array with O(1) hash set operations

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Hash set can store up to n/2 + 1 elements in the worst case

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 3 ร— 104
  • -3 ร— 104 โ‰ค nums[i] โ‰ค 3 ร— 104
  • Each element in the array appears twice except for one element which appears only once
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 28
73.9K Views
High Frequency
~12 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen