See the original problem on HackerRank.
Solutions
This problem is very easy but, as we’ll see in a minute, it can be solved in a very clever way.
The easiest approach uses extra space, a frequency table. The core of the algorithm in C++:


This solution is linear.
Other data structures work as well, such as static arrays (when the domain is smaller) and hash maps.
Clearly, the domain plays a crucial role: here, the extra space used is constant because the domain is fixed and does not vary with the input. It’s a tradeoff.
Another working solution avoids allocating extra space by exploiting two observations over the input format:
 since we have \(N+1\) unique elements in a \(2 \cdot N\) array and the repeating one is present \(N\) times, this means that there can be no other element repeating
 if half of the array is repeated, it doesn’t matter how we shuffle it, for one of the repeated elements there has to be another repeated element at least 3 positions away, otherwise the array isn’t \(2 \cdot N\).
Thus, we only have to compare elements with their neighbors that are distance 1, 2, or 3 away:


Practically speaking, this solution is a bit slower than the other one (mostly because it has an inner loop) but it’s very interesting to find.
As we have seen, both the solutions exploit some data of the input domain.
Another similar solution that iterates on the array only once:


The only case where we need the explicit if condition above is when N=2
. For example:


In this case, the result is the last number, so we just return it in the end:


By the way, Python allows us to remove the condition due to the behavior of the slice operator (e.g. A[1]
returns the last element):


An esotheric solution consists in observing that if you pick two numbers randomly, there is a 25% chance you bump into the repeated number. So, in average, we will find the answer in 4 attempts, thus O(4) runtime!
Taken from here:

