Find the Duplicate Number
The key idea
Read each index
i as a node pointing to node nums[i]. Because every value is in [1, n] and there are n + 1 slots, this functional graph must contain a cycle, and the entrance of that cycle is exactly the duplicated value. Floyd's tortoise-and-hare finds that entrance in O(1) space without altering the array.Problem
You are given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.
There is only one repeated number in nums. Return *this* repeated number.
You must solve the problem without modifying the array nums and using only constant extra space.
Constraints
1 <= n <= 10^5nums.length == n + 11 <= nums[i] <= n- All the integers in
numsappear only once except for precisely one integer which appears two or more times.
Examples
Input: nums = [1,3,4,2,2]
Output: 2
Input: nums = [3,1,3,4,2]
Output: 3
Input: nums = [3,3,3,3,3]
Output: 3
Complexity
Time: O(n) Space: O(1)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization