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.
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
Visualization
Tap to expand
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code