@rici is right about using time and space: "This can be done in O (n) time and O (1) space."
However, the question can be expanded to a broader requirement: there is no need for only one duplicate number, and the numbers could not be sequential.
OJ puts it like this here : (Note 3, apparently, can be narrowed down)
Given the nums array containing n + 1 integers, where each integer is between 1 and n (inclusive), prove that there must be at least one duplicate number. Assuming there is only one duplicate number, find the duplicate.
Note:
- You should not modify the array (suppose the array is read-only).
- You should use only constant, O (1) extra space.
- The complexity of the execution must be less than O (n2).
- There is only one duplicate number in the array, but it can be repeated more than once.
The question is very well explained and answered here by Keith Schwartz using the Floyd Loop Search Algorithm :
The main trick we need to use to solve this problem is to notice that, since we have an array of n elements from 0 to n - 2, we can represent the array as a definition of a function f from the set {0, 1 , ..., n - 1} on itself. This function is defined as f (i) = A [i]. Given this setting, the duplicated value corresponds to a pair of indices i! = J such that f (i) = f (j). Therefore, our task is to find this pair (i, j). Once we get it, we can easily find the duplicate value by simply choosing f (i) = A [i].
But how do we find this recurring value? It turns out that this is a well-studied problem in computer science called loop detection. The general view of the problem is as follows. We are given the function f. Define the sequence x_i as
x_0 = k (for some k) x_1 = f(x_0) x_2 = f(f(x_0)) ... x_{n+1} = f(x_n)
Assuming that f maps from region to region, this function will have one of three forms. Firstly, if the region is infinite, then the sequence can be infinitely long and not repeating. For example, the function f (n) = n + 1 for integers has this property - not a single number is duplicated. Secondly, the sequence can be closed, which means that there exists some self such that x_0 = x_i. In this case, the sequence cycles through some fixed set of values ββinfinitely. Finally, the sequence may be "rho-shaped." In this case, the sequence looks something like this:
x_0 -> x_1 -> ... x_k -> x_{k+1} ... -> x_{k+j} ^ | | | +-----------------------+
That is, the sequence begins with a chain of elements that enters the cycle, and then cyclically continues indefinitely. We will denote the first element of the cycle, which is achieved in the sequence of "record" of the cycle.
The python implementation can also be found here :
def findDuplicate(self, nums):