I had an interview and there was the following question:
Find unique numbers from sorted array in less than O(n) time.
Ex: 1 1 1 5 5 5 9 10 10 Output: 1 5 9 10
I gave the solution but that was of O(n).
Edit: Sorted array size is approx 20 billion and unique numbers are approx 1000.
We can use bitwise AND to find the unique element in O(n) time and constant extra space. Create an array count[] of size equal to number of bits in binary representations of numbers. Fill count array such that count[i] stores count of array elements with i-th bit set. Form result using count array.
One simple solution is to use two nested loops. For every element, check if it repeats or not. If any element repeats, return false. If no element repeats, return false.
An Efficient Solution can find the required element in O(Log n) time. The idea is to use Binary Search.
The way to find the unique element is by using the XOR bitwise operator which returns 1 only if one of the element is 1 and false otherwise. In the loop, each of the integers in the array are XORed with uniqueId starting at 0. Then, 0 is XOR'ed with 34.
Divide and conquer:
data[0]..data[data.length-1]
). Solves in O(log(n)) in the average case, and O(n) only in the worst case (when each element is different).
Java code:
public static List<Integer> findUniqueNumbers(int[] data) {
List<Integer> result = new LinkedList<Integer>();
findUniqueNumbers(data, 0, data.length - 1, result, false);
return result;
}
private static void findUniqueNumbers(int[] data, int i1, int i2, List<Integer> result, boolean skipFirst) {
int a = data[i1];
int b = data[i2];
// homogenous sequence a...a
if (a == b) {
if (!skipFirst) {
result.add(a);
}
}
else {
//divide & conquer
int i3 = (i1 + i2) / 2;
findUniqueNumbers(data, i1, i3, result, skipFirst);
findUniqueNumbers(data, i3 + 1, i2, result, data[i3] == data[i3 + 1]);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With