Find the number that appears once, and the other numbers twice
Problem Statement:β
Given a non-empty array of integersΒ arr, every element appears twice except for one. Find that single one.
Example 1:
Input Format: arr[] = {2,2,1}
Result: 1
Explanation: In this array, only the element 1 appear once and so it is the answer.
Example 2:
Input Format: arr[] = {4,1,2,1,2}
Result: 4
Explanation: In this array, only element 4 appear once and the other elements appear twice. So, 4 is the answer.
β Solution: Bit Manipulation (XOR)β
class Solution {
public:
int singleNumber(vector<int>& numbers) {
// XOR of all numbers β duplicates cancel out, only the unique one remains
int uniqueNumber = 0;
for (int i = 0; i < numbers.size(); i++) {
uniqueNumber ^= numbers[i]; // XOR each number into the result
}
return uniqueNumber;
}
};
π How It Worksβ
- XOR has properties:
a ^ a = 0a ^ 0 = a- XOR is commutative and associative, so order doesnβt matter.
- In an array where every element appears twice except one, XOR-ing all elements will cancel out the pairs and leave the single unique number.
π§© Key Formulaβ
uniqueNumber = nums[0] ^ nums[1] ^ ... ^ nums[n-1]
β All pairs cancel out due to x ^ x = 0
β±οΈ Time & Space Complexityβ
| Metric | Value |
|---|---|
| β± Time | O(n) |
| π Space | O(1) |
β οΈ Edge Casesβ
- All elements are duplicates except one β works β
- Only one element in the array β returns that element β
- Array not sorted β no issue, XOR works regardless of order β
π‘ Other Approachesβ
| Approach | Time | Space | Notes |
|---|---|---|---|
| XOR (this) | O(n) | O(1) | β Most optimal |
| HashMap (count freq) | O(n) | O(n) | β But extra space needed |
| Sorting + Compare Adj | O(n log n) | O(1) | β Slower due to sorting |
π Related Problemsβ
π¬