Find the Duplicate Number
LeetCode 287 · Medium · solution, intuition & step-by-step walkthrough
Floyd's cycle detection on index → value pointers.
This is how I solved Find the Duplicate Number (LeetCode 287), a medium problem from the Cyclic Sort / Index Marking pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Treat the array as a function i → nums[i]. Because values are in 1..n with one repeat, following the pointers must enter a cycle, and the cycle's entrance is the duplicate. Floyd's tortoise and hare finds it without extra memory or modifying the array.
Approach
- 1
Phase 1: slow = nums[slow], fast = nums[nums[fast]] until they meet.
- 2
Phase 2: reset one pointer to the start.
- 3
Move both one step at a time; they meet at the cycle entrance — the duplicate.
How I solved it
Floyd's tortoise and harePythonO(n) time · O(1) space
class Solution:
def findDuplicate(self, nums):
slow = nums[0]
fast = nums[0]
while True: # do ... while
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
fast = nums[0]
while slow != fast:
fast = nums[fast]
slow = nums[slow]
return slowFind the Duplicate Number — FAQ
What is the intuition behind Find the Duplicate Number?
Treat the array as a function i → nums[i]. Because values are in 1..n with one repeat, following the pointers must enter a cycle, and the cycle's entrance is the duplicate. Floyd's tortoise and hare finds it without extra memory or modifying the array.
How do you solve Find the Duplicate Number (LeetCode 287)?
1. Phase 1: slow = nums[slow], fast = nums[nums[fast]] until they meet. 2. Phase 2: reset one pointer to the start. 3. Move both one step at a time; they meet at the cycle entrance — the duplicate.
What is the time and space complexity of Find the Duplicate Number?
Time: O(n). Space: O(1). (Accepted approach: Floyd's tortoise and hare.)
What are common mistakes in Find the Duplicate Number?
The 'do … while' first step matters: both start at nums[0].