Every integer in this random array of integers is repeated except for one. This single number does not have a duplicate. Who is the loner?
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
neat solution!!
Brilliant !
This only works when there is an even quantity of each repeating number, right? If there are three repetitions of a number, your code will produce the wrong result. It's also not clear in the question that all numbers but one come in pairs.
1 2 3 4 5 |
|
This takes quadratic time, which is very slow. I believe it takes a very long time (at least an hour); how did you manage to be patient enough to wait for it? Or rather, how long did it take?
Log in to reply
I haven't thought of time complexity of this program, but it executed under 1 minute.
The XOR method given by the setter is very neat solution, runs in O(n) time and does not require knowledge of the size of the greatest value, and it's single pass, and can operate on the data directly and take O(1) storage.
A naive algorithm would be a simple three pass one which has O(value-range) time and O(value-range) space. Pass 1: find range values and allocate and zero out bit vector of length value-range. Pass 2: Set vector[value-minRange] = 1 xor vector[value-minRange]; Pass 3: Scan vector to find the first bit <> 0.
A two pass algorithm. Could use a hash table and keep a count of the number of time a value has been seen. Then scan the table to find which key has a count-value of 1. Looks like O(n) time and O(n) space. (A hash table can iterate over all entries but not in a controlled order).
It is hard to know the computation complexity of a given library or language's built-in algorithm and it may well be that set(data) is O(n^2) or worse.
1 2 |
|
Another way of doing this is by first sorting the array. Then scan for n and n+1 term to be equal, else break, and at the end of loop n=n+2.
Log in to reply
Sorting the array takes
O
(
n
l
g
n
)
time. Assuming a perfect hash table (used for
Counter
), it takes only
O
(
n
)
time.
Problem Loading...
Note Loading...
Set Loading...
Behold the power of XOR!
where the variable
array
is the array of numbers. ..
.
.
.
.
.
Explanation
Notice that the X O R operation is commutative a X O R b = b X O R a and associative a X O R ( b X O R c ) = c X O R ( a X O R B ) Also notice that the 0 is the identity value for the X O R operation a X O R 0 = a This means we can just X O R every value and obtain the answer because all the pairs will reduce to 0 , except for the loner .