1

I'm new at algorithms and want to know how to solve this task. A detailed Java solution is desirable.

You have been given an integer n≄2 and an integer array A[0..nāˆ’1] which is sorted in nondecreasing order . All numbers repeat 1 time but one number repeats 2 times, how do you find the number that repeat 2 times. Using data structures and built-in functions was not allowed. Complexity of algorithm should be O(lg(n))

  • 1
    Could you clarify what you mean with repeat one time? Is one number that only repeats one time unique in the array, or are there two instances? – Marcello Zago Sep 27 '21 at 20:43
  • 2
    Does this answer your question? [Finding multiple entries with binary search](https://stackoverflow.com/questions/12144802/finding-multiple-entries-with-binary-search) – c3R1cGFy Sep 27 '21 at 20:54

1 Answers1

3

You can use a custom binary search algorithm.

We can observe that if there would be only values that repeated once (which occur twice), then the size of the array is even, and we have for each even index i: A[i] == A[i+1].

Since there is exactly one triplet, the array's size is odd, and so if we find an even index i for which A[i] == A[i+1] we know that the triplet did not occur at the left side of i. If however A[i] != A[i+1], then we are sure the triplet occurred at the left side of i.

This is all we need to perform a binary search. We should just make sure we always make our checks at even indices.

Here is an implementation in JavaScript:

function binarySearchTriplet(arr) {
    let lo = 0, hi = arr.length - 1; // even
    while (lo < hi) {
        // Take mid, but force it to be even
        mid = (lo + hi) >> 2 << 1;
        if (arr[mid] === arr[mid+1]) {
            lo = mid + 2;
        } else {
            hi = mid;
        }
    }
    return arr[lo];
}

let arr = [1,1,4,4,4,5,5,7,7,2,2,6,6,8,8];
console.log(binarySearchTriplet(arr)); // 4
trincot
  • 317,000
  • 35
  • 244
  • 286