The fastest way is an O(N) in-place pigeonhole sort.
Start at the first location of the array, a[0]
. Say it has the value 5
. You know that 5
belongs at a[4]
, so swap locations 0
and 4
. Now a new value is in a[0]
. Swap it to where it needs to go.
Repeat until a[0] == 1
, then move on to a[1]
and swap until a[1] == 2
, etc.
If at any point you end up attempting to swap two identical values, then you have found the duplicate!
Runtime: O(N) with a very low coefficient and early exit. Storage required: zero.
Bonus optimization: count how many swaps have occurred and exit early if n_swaps == array_size
. This resulted in a 15% improvement when I implemented a similar algorithm for permuting a sequence.