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
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
.