24. Unique Number III
The problem can be found at the following link: ๐ Question Link
๐งฉ Problem Description
Given an array arr[]
where every element occurs thrice except one element which occurs only once, your task is to find that unique element.
๐ Examples
Example 1:
Input:
arr[] = [1, 10, 1, 1]
Output:
10
Explanation:
All numbers except 10
occur three times. Hence, the answer is 10
.
Example 2:
Input:
arr[] = [3, 2, 1, 34, 34, 1, 2, 34, 2, 1]
Output:
3
Explanation:
Only 3
occurs once. All other numbers appear exactly three times.
๐ Constraints
$( 1 \leq \text{arr.size()} \leq 10^5 )$
$( \text{arr.size()}$ % 3 = 1 )
$( -10^9 \leq \text{arr[i]} \leq 10^9 )$
โ
My Approach:
Optimized Bitwise Counting
This method uses bitwise manipulation to keep track of bits appearing once, twice, and thrice across the array.
Algorithm Steps:
Initialize two variables
ones
andtwos
to 0.For each element:
Update
ones
as:(ones ^ num) & ~twos
Update
twos
as:(twos ^ num) & ~ones
After the loop,
ones
will hold the element that appears only once.
๐งฎ Time and Auxiliary Space Complexity
Expected Time Complexity: O(N), since we iterate once through the array.
Expected Auxiliary Space Complexity: O(1), as we only use a constant number of variables.
๐ง Code (C++)
class Solution {
public:
int getSingle(vector<int> &arr) {
int ones = 0, twos = 0;
for (int num : arr) {
ones = (ones ^ num) & ~twos;
twos = (twos ^ num) & ~ones;
}
return ones;
}
};
๐งโ๐ป Code (Java)
class Solution {
public int getSingle(int[] arr) {
int ones = 0, twos = 0;
for (int num : arr) {
ones = (ones ^ num) & ~twos;
twos = (twos ^ num) & ~ones;
}
return ones;
}
}
๐ Code (Python)
class Solution:
def getSingle(self, arr):
ones = twos = 0
for num in arr:
ones = (ones ^ num) & ~twos
twos = (twos ^ num) & ~ones
return ones
๐ง 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