Reputation: 3264
My friend got a question in a test , the question was:
You get an unsorted array with integer values as pairs , and 1 value as single for example:
[1,1,5,5,2,2,4,4,7,12,12,8,8]
The output is:
7
Now I know binary search can do it with O(log n) but the array need to be sorted.
So how can it be done in O(log n) on this unsorted array ?
Upvotes: 1
Views: 3409
Reputation:
Let us consider the auxiliary array formed by taking every other number and assigning 0 if equal to the next and 1 otherwise.
[1,1,5,5,2,2,4,4,7,12,12,8,8]
[0, 0, 0, 0, 1, 1 ]
This auxiliary array is clearly sorted and the first 1 can be found by binary search.
Of course the array mustn't be constructed explicitly, as this would take O(N).
Upvotes: 1
Reputation: 34155
You can also do a binary search in an unsorted array if the value pairs are next to each other:
<n elements> <1 element> <n elements>
:Upvotes: 5
Reputation:
If suffices to notice that all pairs on the left of the singleton are on even/odd indexes and those on the right are on odd/even.
As the parity of the pair to which an arbitrary element belongs can be found in constant time, a dichotomic process to find the parity transition is indeed possible.
This only holds if the neighboring pairs are different or if the runs of equal pairs never exceed a length O(1). For instance with a single 7 among all pairs of 8's, only a linear search can do.
Upvotes: 3