22. Unique Number I
The problem can be found at the following link: Question Link
Problem Description
You are given an unsorted array of positive integers in which every element occurs exactly twice, except for one element that appears only once. Your task is to find that unique number.
Examples
Example 1:
Input:
arr[] = [1, 2, 1, 5, 5]Output:
2Explanation:
All elements except 2 occur twice. Hence, the unique number is 2.
Example 2:
Input:
Output:
Explanation:
Only 20 appears once. All other elements occur twice.
Constraints:
$(1 \leq \text{arr.size()} \leq 10^6)$
$(0 \leq \text{arr}[i] \leq 10^9)$
My Approach
Bit Manipulation (XOR Method)
The XOR of two equal numbers is 0.
XOR of a number with 0 is the number itself.
Thus, XOR-ing all numbers will cancel out the duplicates and leave the unique one.
Algorithm Steps:
Initialize result as 0.
Iterate over the array and XOR each number with the result.
Final result is the unique number.
Time and Auxiliary Space Complexity
Expected Time Complexity:
O(n), as we traverse the array once.Expected Auxiliary Space Complexity:
O(1), as we only use a constant amount of extra space.
Code (C++)
โก Alternative Approaches
๐ 2๏ธโฃ Hash Map Frequency Count
Algorithm Steps:
Traverse the array and store frequencies in a hash map.
Return the element with frequency
1.
๐ Complexity Analysis:
Time Complexity:
O(n)Space Complexity:
O(n)
โ Why This Approach?
Straightforward and useful when duplicates can appear more than twice or in non-pair counts.
๐ 3๏ธโฃ Sorting and Pair Check
Algorithm Steps:
Sort the array.
Compare elements in pairs. The one not matching its pair is unique.
๐ Complexity Analysis:
Time Complexity:
O(n log n)Space Complexity:
O(1)
โ Why This Approach?
Good when extra space isnโt allowed but we can afford sorting time.
๐ Comparison of Approaches
Approach
โฑ๏ธ Time Complexity
๐๏ธ Space Complexity
โ Pros
โ ๏ธ Cons
XOR Method
๐ข O(n)
๐ข O(1)
Fastest, minimal space
Only works with exact pairs
Hash Map Frequency
๐ข O(n)
๐ด O(n)
Easy to extend to generic cases
Extra memory used
Sorting + Pairing
๐ด O(n log n)
๐ข O(1)
No extra memory, simple comparison
Slower due to sorting
โ
Best Choice?
Scenario
Recommended Approach
โ Optimal runtime and no extra space
๐ฅ XOR Method
โ Handles non-standard frequencies
๐ฅ Hash Map Frequency
โ Array can be modified and space is a concern
Sorting + Pair Check
๐น Overall Best for performance and space: XOR Method ๐น Best for generic input flexibility: Hash Map Approach
Code (Java)
Code (Python)
Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letโs make this learning journey more collaborative!
โญ If you find this helpful, please give this repository a star! โญ
๐Visitor Count
Last updated