0

This is a practice question for the understanding of Divide and conquer algorithms.

You are given an array of N sorted integers. All the elements are distinct except one element is repeated twice. Design an O (log N) algorithm to find that element.

I get that array needs to be divided and see if an equal counterpart is found in the next index, some variant of binary search, I believe. But I can't find any solution or guidance regarding that.

6
  • Are these consecutive integers? Commented Dec 6, 2015 at 17:18
  • No. This is the exact text of the question and it doesn't mention consecutive integers. Commented Dec 6, 2015 at 17:19
  • I don't think there is a logN solution when it is not consecutive numbers. Commented Dec 6, 2015 at 17:22
  • 3
    To achieve log(N) you need some criterion to discard half of the array at each iteration. With random (though sorted) integers there is no such criterion, and you need to ultimately check all the elements, which makes it worst case O(N). Possibly the author of the question was thinking of an array of 1..N-1 elements (i.e., consecutive). Commented Dec 6, 2015 at 17:23
  • This seems too similar to the consecutive numbers question, probably that was left out on mistake, since if not - then the consecutive sorted array question has redundant information, and it doesn't :) Commented Dec 6, 2015 at 17:24

2 Answers 2

3

You can not do it in O(log n) time because at any step even if u divide the array in 2 parts, u can not decide which part to consider for further processing and which should be left. On the other hand if the consecutive numbers are all present in the array then by looking at the index and the value in the index we can decide if the duplicate number is in left side or right side of the array.

Sign up to request clarification or add additional context in comments.

Comments

0

D&C should look something like this

int Twice (int a[],int i, int j) {
    if (i >= j)
       return -1;
    int k = (i+j)/2;
    if (a[k] == a[k+1]) 
       return k;
    if (a[k] == a[k-1])
       return k-1;
    int m = Twice(a,i,k-1);
    int n = Twice(a,k+1,j);
    return m != -1 ? m : n;
}


int Twice (int a[], int n) {
    return Twice(a,0,n);
}

But it has complexity O(n). As it is said above, it is not possible to find O(lg n) algorithm for this problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.