Reputation: 45
I am studying for an exam and found this question with the following solution that I didn't understand it at all. Any help on what they did and why?
I have an unsorted array where each integer in the array appears in pairs (next to each other); in this array, there is only one integer that appears without a pair; also, there can't be two pairs of the same integer next to each other!
I need to find this odd integer in the best time (best time complexity) for example, given the following array:
8 8 5 5 3 6 6 -1 -1 7 7
the output is 3!
The code:
int FindOddOccuring(int arr[], int n) {
int left = 0, right = n / 2;
while (left < right)
{
int mid = (left + right) / 2;
if (arr[2 * mid + 1] == arr[2 * mid])
left = mid + 1;
else
right = mid;
}
return arr[2 * right];
}
Upvotes: 2
Views: 1977
Reputation: 14493
The above algorithm completes in O(Log2(N)), much better than traditional scan which will be O(n)
The "trick" is to perform binary search, and be able to tell if the odd value is in the left or in the right. The test on the middle pair enable the binary search
Upvotes: 1
Reputation: 147
The key of this is in the line:
if (arr[2 * mid + 1] == arr[2 * mid])
Give the fact that numbers are inserted in pairs and can only be one non-paired number, if you check for two consecutives between the two last numbers of the first half in the array and they are not equal, then your rebel number will inevitably be in the second half of the array ... Why?!: because the 'rebel' number is the one wich breaks the a[i]=a[i+1] invariant, and you are checkin always from an even position to the previous one... Is my explanation clear enough? Is it too trivial? I hope it helps!
Upvotes: 1