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
onesandtwosto 0.For each element:
Update
onesas:(ones ^ num) & ~twosUpdate
twosas:(twos ^ num) & ~ones
After the loop,
oneswill 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