Find the Duplicate Number
Difficulty: Medium · Pattern: Fast & Slow Pointers · LeetCode #287
nums has n + 1 integers, each in [1, n], so at least one value repeats. Exactly one value is repeated (possibly more than twice). Return it without modifying nums, using O(1) extra space.
Examples
text
[1,3,4,2,2] → 2
[3,1,3,4,2] → 3
[3,3,3,3,3] → 3Hints
- Sorting modifies the array. A hash set uses O(n) space. Neither is allowed.
- View each index i as a node with an edge to
nums[i]. Index 0 is never a target, so it's the start. Two indices pointing to the same value form... a cycle entry.
Approach
Floyd on the functional graph f(i) = nums[i]: starting from index 0, the path must eventually cycle, because there are n+1 nodes. The node where the cycle begins has two incoming edges: one from the tail of the path, one from inside the cycle. Two indices point to it, so it is the duplicated value.
slow = nums[slow],fast = nums[nums[fast]]until they meet.- Reset
slow = 0, and step both one at a time until they're equal. That's the duplicate.
Alternative: binary search on the value. Count the elements ≤ mid. If the count is > mid, the duplicate is ≤ mid (pigeonhole). That's O(n log n).
Complexity
Time: O(n). Space: O(1).
Python solution
def findDuplicate(nums):
slow = fast = 0
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
slow = 0
while slow != fast:
slow = nums[slow]
fast = nums[fast]
return slowJavaScript solution
function findDuplicate(nums) {
let slow = 0, fast = 0;
do { slow = nums[slow]; fast = nums[nums[fast]]; } while (slow !== fast);
slow = 0;
while (slow !== fast) { slow = nums[slow]; fast = nums[fast]; }
return slow;
}