Find the Duplicate Number
Description
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Example 1:
Example 2:
Note:
You must not modify the array (assume the array is read only).
You must use only constant, O(1) extra space.
Your runtime complexity should be less than O(n2).
There is only one duplicate number in the array, but it could be repeated more than once.
Solutions
Binary search
Idea: let the number of numbers mid
be count
. If count > mid
, then the duplicate must be in [1, mid]
. Otherwise the duplicate must be in [mid + 1, n]
.
Fast and slow pointers
Idea: consider a graph with nodes 0, 1, ..., n
. There is an edge from i
to j
if nums[i] = j
. The graph must be a -shaped linked-list. nums[i] > 0
for all i
, so node 0
has no incoming edges. So the head node is 0
.
Let be the distances traveled by fast and slow pointers when they meet, be the length of the cycle. (the fast pointer travel more cycles.). So .
Set the slow pointer back to node 0
, and let both pointers move at the same speed. They must meet at the entry of the cycle. Let be the distance between the head node and the entry node. When the slow pointer reaches the entry node, the fast pointer travels . So the fast pointer is also at the entry node.
Reference: detailed explanation
Bit counting
One interesting solution but I can't understand. O(32*N) solution using bit manipulation in 10 lines.
Last updated