Source : Microsoft Interview Question
Given a sorted array, in which every element is present twice except one which is present single time
Yes, you can use the sortedness to reduce the complexity to O(log n)
by doing a binary search.
Since the array is sorted, before the missing element, each value occupies the spots 2*k
and 2*k+1
in the array (assuming 0-based indexing).
So you go to the middle of the array, say index h
, and check either index h+1
if h
is even, or h-1
if h
is odd. If the missing element comes later, the values at these positions are equal, if it comes before, the values are different. Repeat until the missing element is located.