Given an array where every element occurs three times, except one element which occurs only once. Find the element that occurs once. Expected time complexity is O(n) and O(1) extra space.
Examples:
Input: arr[] = {12, 1, 12, 3, 12, 1, 1, 2, 3, 3}
Output: 2
We can use sorting to do it in O(nLogn) time. We can also use hashing, it has the worst case time complexity of O(n), but requires extra space.
The idea is to use bitwise operators for a solution that is O(n) time and uses O(1) extra space. The solution is not easy like other XOR based solutions, because all elements appear odd number of times here.
public static void main(String[] args){
int[] a = {12,12,23,34,45,23,34,45,444,555,444,555,2,2,3,333,333};
int[] result = new int[16];
//although there are two for loops, time complexity if O(n) as inner loop runs a fixed number of times
for(int i = 0;i <= a.length - 1;i++){
for(int j = 15;j > 0;j--){
result[j] += (a[i] & 1);
a[i] = a[i] >> 1;
}
}
The result array contains number of set bits for all numbers in array. Since, the numbers are repeated twice, we take modulus of 2 of every bit of result. If they were repeated thrice, we would have to take modulus of 3.
int r = 0;
for(int j = 15;j >= 0;j--){
r += (Math.pow(2, 15-j) * (result[j]%2));
}
System.out.println(r);
}
Examples:
Input: arr[] = {12, 1, 12, 3, 12, 1, 1, 2, 3, 3}
Output: 2
We can use sorting to do it in O(nLogn) time. We can also use hashing, it has the worst case time complexity of O(n), but requires extra space.
The idea is to use bitwise operators for a solution that is O(n) time and uses O(1) extra space. The solution is not easy like other XOR based solutions, because all elements appear odd number of times here.
public static void main(String[] args){
int[] a = {12,12,23,34,45,23,34,45,444,555,444,555,2,2,3,333,333};
int[] result = new int[16];
//although there are two for loops, time complexity if O(n) as inner loop runs a fixed number of times
for(int i = 0;i <= a.length - 1;i++){
for(int j = 15;j > 0;j--){
result[j] += (a[i] & 1);
a[i] = a[i] >> 1;
}
}
The result array contains number of set bits for all numbers in array. Since, the numbers are repeated twice, we take modulus of 2 of every bit of result. If they were repeated thrice, we would have to take modulus of 3.
int r = 0;
for(int j = 15;j >= 0;j--){
r += (Math.pow(2, 15-j) * (result[j]%2));
}
System.out.println(r);
}