Sunday, April 2, 2017

Finds unique value from a sorted array that has duplicates such as [1,1,2,2,3,3]

    /**
     * Finds unique value from a sorted array that has duplicates such as [1,1,2,2,3,3]<br/>
     * The approach is to have a O(log n) algorithm - perform operation as a binary search
     * @param a
     * @return
     */
    public static int findUnique(int []a) {
        if (a == null || a.length == 0) {
            throw new RuntimeException("Invalid parameter");
        }

        int length = a.length;
        if (length %2 == 0) return Integer.MIN_VALUE;

        // If only single element array, return the element
        if (length == 1) return a[0];

        // This is to handle the case when the unique element is either first or last.
        if (a[0] != a[1]) return a[0];
        if (a[length - 1] != a[length - 2]) return a[length - 1];
     
        int s = 0, e = length - 1;

        // Else perform binary search
        for (; s < e;) {
            int m = (s + e) / 2;
            int mid = a[m];

            if (m == s || m == e) return mid;

            if (mid == a[m ^ 1]) {
                s = m + 1;
            } else {
                e = m;
            }
        }

        return a[s];
    }

No comments:

Post a Comment