Leetcode 287. Find the Duplicate Number
Given an array of integers nums
containing n + 1
integers where each integer is in the range [1, n]
inclusive. There is only one duplicate number in nums
, but it could be repeated more than once. Return the duplicate number.
You must solve the problem without modifying the array nums
and use only constant extra space.
n
?
1 <= n <= 10^5
.n+1
where 1 <= n <= 10^5
.We will use Floyd’s Tortoise and Hare (Cycle Detection) Algorithm to solve this problem. This algorithm leverages the idea that if you treat the array as a linked list where the value at each index points to the next index, the duplicate number will form a cycle.
Here’s the implementation of the strategy in Java:
public class Solution {
public int findDuplicate(int[] nums) {
// Phase 1: Finding the intersection point of the two runners.
int tortoise = nums[0];
int hare = nums[0];
do {
tortoise = nums[tortoise];
hare = nums[nums[hare]];
} while (tortoise != hare);
// Phase 2: Finding the entrance to the cycle.
tortoise = nums[0];
while (tortoise != hare) {
tortoise = nums[tortoise];
hare = nums[hare];
}
return hare;
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?