Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding unique numbers from sorted array in less than O(n)

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.

like image 881
Deepu--Java Avatar asked Nov 16 '14 14:11

Deepu--Java


People also ask

How do you find unique numbers in an array?

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.

How do you find uniqueness of an 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.

In which of the following we can search an element in less than equal to O logn time?

An Efficient Solution can find the required element in O(Log n) time. The idea is to use Binary Search.

How do you find unique elements in an array using XOR?

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.


1 Answers

Divide and conquer:

  • look at the first and last element of a sorted sequence (the initial sequence is data[0]..data[data.length-1]).
  • If both are equal, the only element in the sequence is the first (no matter how long the sequence is).
  • If the are different, divide the sequence and repeat for each subsequence.

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]);
    }
}
like image 153
Peter Walser Avatar answered Oct 21 '22 02:10

Peter Walser