Finding the Duplicate Number Using Floyd's Tortoise and Hare Algorithm
In this tutorial, we'll explore how to find a duplicate number in an array efficiently without modifying the array and using only constant extra space. We'll achieve this by applying a cycle detection algorithm known as Floyd's Tortoise and Hare.
Problem Statement
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 the array, but it could be repeated more than once.
- You must not modify the array (read-only).
- You must use only constant, O(1) extra space.
Goal: Find the duplicate number.
Example:
Input: nums = [1,3,4,2,2]
Output: 2
Understanding the Approach
To solve this problem efficiently, we'll:
- Visualize the array as a linked list where each index points to the value at that index.
- Use Floyd's Tortoise and Hare algorithm to detect a cycle in this "linked list".
- The start of the cycle corresponds to the duplicate number.
Why Does This Work?
- Since the numbers are from
1 to n and the array size is n + 1, there must be at least one duplicate (by the Pigeonhole Principle).
- By interpreting the array indices and values as a linked list, the duplicate number creates a cycle.
The Algorithm
Here's the method we'll use:
-
Initialization:
- Start two pointers
slow and fast at the beginning of the array.
-
First Phase (Cycle Detection):
- Move
slow by one step: slow = nums[slow].
- Move
fast by two steps: fast = nums[nums[fast]].
- Continue until
slow and fast meet. This indicates a cycle.
-
Second Phase (Finding the Duplicate):
- Start a new pointer
slow2 at the beginning.
- Move both
slow and slow2 by one step: slow = nums[slow], slow2 = nums[slow2].
- Continue until
slow and slow2 meet.
- The meeting point is the duplicate number.
Code Explanation
Here's the complete code, with explanations:
function findDuplicate(nums: number[]): number {
// Initialize two pointers at the start of the array
let slow = 0;
let fast = 0;
// First Phase: Detect the cycle
while (true) {
// Move slow pointer by one step
slow = nums[slow];
// Move fast pointer by two steps
fast = nums[nums[fast]];
// Check if the two pointers meet
if (slow == fast) {
// Cycle detected
break;
}
}
// Second Phase: Find the entrance to the cycle (duplicate number)
let slow2 = 0;
while (true) {
// Move both pointers by one step
slow = nums[slow];
slow2 = nums[slow2];
// Check if the pointers meet at the duplicate number
if (slow == slow2) {
break;
}
}
// The meeting point is the duplicate number
return slow;
}
First Phase: Cycle Detection
- Purpose: To find a point within the cycle created by the duplicate number.
- Mechanism:
slow moves one step at a time.
fast moves two steps at a time.
- Outcome: When
slow equals fast, we have confirmed a cycle exists.
Second Phase: Finding the Duplicate Number
- Purpose: To find the exact starting point of the cycle, which is the duplicate number.
- Mechanism:
- Initialize a new pointer
slow2 at the start of the array.
- Move both
slow and slow2 one step at a time.
- Outcome: When
slow equals slow2, we've found the duplicate number.
How the Algorithm Works
Visualizing the Array as a Linked List
- Each index represents a node in the linked list.
- The value at each index points to the next node.
- The duplicate number creates a cycle because two indices point to the same value.
Example:
For nums = [1, 3, 4, 2, 2],
- Start at index
0 (value 1), which points to index 1.
- Index
1 (value 3) points to index 3.
- Index
3 (value 2) points to index 2.
- Index
2 (value 4) points to index 4.
- Index
4 (value 2) points back to index 2, creating a cycle.
Detailed Walkthrough
First Phase:
-
Iteration 1:
slow = nums[0] = 1
fast = nums[nums[0]] = nums[1] = 3
-
Iteration 2:
slow = nums[1] = 3
fast = nums[nums[3]] = nums[2] = 4
-
Iteration 3:
slow = nums[3] = 2
fast = nums[nums[4]] = nums[2] = 4
-
Iteration 4:
slow = nums[2] = 4
fast = nums[nums[2]] = nums[4] = 2
-
Iteration 5:
slow = nums[4] = 2
fast = nums[nums[2]] = nums[4] = 2
-
Cycle Detected:
slow and fast meet at index 2 (value 2).
Second Phase:
-
Initialize:
-
Iteration 1:
slow = nums[2] = 4
slow2 = nums[0] = 1
-
Iteration 2:
slow = nums[4] = 2
slow2 = nums[1] = 3
-
Iteration 3:
slow = nums[2] = 4
slow2 = nums[3] = 2
-
Iteration 4:
slow = nums[4] = 2
slow2 = nums[2] = 4
-
Iteration 5:
slow = nums[2] = 4
slow2 = nums[4] = 2
-
Duplicate Found:
slow and slow2 meet at index 2 (value 2).
Time and Space Complexity
-
Time Complexity: O(n)
- Both phases run in linear time relative to the length of
nums.
-
Space Complexity: O(1)
- No additional data structures are used; only a constant amount of extra space is needed.
Conclusion
By modeling the array as a linked list and applying Floyd's Tortoise and Hare algorithm, we can efficiently find the duplicate number without modifying the array and using only constant extra space.
This method is elegant and avoids the need for hash tables or modifying the input, making it suitable for scenarios where the array is read-only or large.
Remember: The key insight is recognizing that the duplicate number creates a cycle in the array when visualized as a linked list, allowing us to use cycle detection techniques to find the duplicate.
Happy Coding!