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