πDay 4. Unique Number II π§
The problem can be found at the following link: Question Link
π‘ Problem Description:
Given an array arr[]
of size 2*N + 2, where 2*N elements appear in pairs and two elements appear only once, your task is to find those two distinct unique numbers and return them in increasing order.
π Example Walkthrough:
Example 1:
Input:
arr[] = [1, 2, 3, 2, 1, 4]
Output:
[3, 4]
Explanation:
3 and 4 occur exactly once in the array. All other elements appear in pairs.
Example 2:
Input:
arr[] = [2, 1, 3, 2]
Output:
[1, 3]
Explanation:
1 and 3 occur only once. 2 appears twice.
Example 3:
Input:
arr[] = [2, 1, 3, 3]
Output:
[1, 2]
Explanation:
1 and 2 occur once. 3 appears twice.
Constraints:
$(2 \leq \text{arr.size()} \leq 10^6)$
$(1 \leq \text{arr}[i] \leq 5 \times 10^6)$
arr.size()
is even
π― My Approach:
XOR Partition Method
This is the most efficient and clever approach using bit manipulation.
Algorithm Steps:
XOR all elements β result is XOR of the two unique numbers:
x = a ^ b
.Find the rightmost set bit in
x
.Partition the array into two groups based on this bit.
XOR each group β you get
a
andb
separately.Return the numbers in increasing order.
π Time and Auxiliary Space Complexity
Expected Time Complexity:
O(n)
, as we iterate through the array a constant number of times.Expected Auxiliary Space Complexity:
O(1)
, as we only use a constant number of variables.
π Solution Code
Code (C++)
class Solution {
public:
vector<int> singleNum(vector<int>& A) {
int x = 0, a = 0, b = 0;
for (int n : A) x ^= n;
for (int n : A) (n & (x & -x) ? a : b) ^= n;
return a < b ? vector<int>{a, b} : vector<int>{b, a};
}
};
Code (Java)
class Solution {
public int[] singleNum(int[] arr) {
int x = 0, a = 0, b = 0;
for (int n : arr) x ^= n;
for (int n : arr) if ((n & (x & -x)) != 0) a ^= n; else b ^= n;
return a < b ? new int[]{a, b} : new int[]{b, a};
}
}
Code (Python)
class Solution:
def singleNum(self, arr):
x = 0
for n in arr: x ^= n
a = b = 0
for n in arr:
(a, b) = (a ^ n, b) if n & (x & -x) else (a, b ^ n)
return [a, b] if a < b else [b, a]
π― 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