Size of an array is n.All elements in the array are distinct in the range of [0 , n-1] except two elements.Find out repeated element without using extra temporary array with con
The best I can do is O(n log n)
in time and O(1)
in space:
The basic idea is to perform a binary search of the values 0
through n-1
, passing over the whole array of n
elements at each step.
i=0
, j=n-1
and k=(i+j)/2
.i
to k
, and count the number of elements in this range.(k-i)*(k-i+1)/2 + i*(k-i+1)
, then the range i
through k
has neither the duplicate nor the omitted value. If the count of elements is less than k-i+1
, then the range has the omitted value but not the duplicate. In either case, replace i
by k+1
and k
by the new value of (i+j)/2
.j
by k
and k
by the new value of (i+j)/2
.i!=j
, goto 2.The algorithm terminates with i==j
and both equal to the duplicate element.
(Note: I edited this to simplify it. The old version could have found either the duplicate or the omitted element, and had to use Vlad's difference trick to find the duplicate if the initial search turned up the omitted value instead.)