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
Sum(1, n) = (n+1)n/2
.Good luck coding!
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.)
Lazy solution: Put the elements to java.util.Set
one by one by add(E)
until getting add(E)
==false.
Sorry no constant-time. HashMap:O(N), TreeSet:O(lgN * N).
Pick two distinct random indexes. If the array values at those indexes are the same, return true.
This operates in constant time. As a bonus, you get the right answer with probability 2/n * 1/(n-1).
Build a lookup table. Lookup. Done.
Non-temporary array solution:
Build lookup into gate array hardware, invoke.
XOR
all the elements together, then XOR
the result with XOR([0..n-1])
.
This gives you missing XOR repeat
; since missing!=repeat
, at least one bit is set in missing XOR repeat
.
Pick one of those set bits. Iterate over all the elements again, and only XOR
elements with that bit set. Then iterate from 1
to n-1
and XOR
those numbers that have that bit set.
Now, the value is either the repeated value or the missing value. Scan the elements for that value. If you find it, it's the repeated element. Otherwise, it's the missing value so XOR
it with missing XOR repeat
.