Find the Duplicate Number (LeetCode 287): Solution and Explanation
An array holds n + 1 integers, each between 1 and n, so at least one value must repeat, and exactly one value does (possibly many times). Find that value without modifying the array and using only constant extra space.
Watch it run step by step
Try your own input and write the code →Intuition
Without the restrictions this is easy. A hash set finds the first repeat in O(n) time and O(n) space, and sorting puts duplicates side by side in O(n log n) time. The problem forbids both extra memory and changing the array, which rules out these and also rules out the trick of marking visited values by negating them.
The breakthrough is to stop seeing the array as a list and start seeing it as a function. Treat each index i as a node with an edge to nums[i]. Because every value is between 1 and n, every edge points to a valid index, so if you start at index 0 and keep following i = nums[i], you walk forever through the array. A walk that never ends in a finite set of nodes must eventually loop.
Now think about where the loop starts. The entrance to a cycle is a node with two incoming edges: one from the path leading in and one from inside the cycle. Two incoming edges means two different indices hold the same value, and that value is the duplicate. Index 0 has no incoming edge, since no value is 0, so starting there guarantees you are on the path that leads into the cycle rather than inside it already.
That turns the problem into finding the start of a cycle in a linked list, which Floyd's tortoise and hare algorithm does with two pointers. A slow pointer moves one step at a time and a fast pointer moves two, and they must meet inside the cycle. Then, if you restart one pointer from the beginning and move both one step at a time, they meet exactly at the cycle's entrance, which is the duplicate value.
Approach: Floyd's cycle detection
- Set both
slowandfasttonums[0], one step into the walk from index 0. - Repeatedly move
slow = nums[slow]andfast = nums[nums[fast]]until the two are equal. This is a meeting point inside the cycle. - Reset
slow = nums[0]while leavingfastat the meeting point. - Move both one step at a time with
slow = nums[slow]andfast = nums[fast]until they are equal. - Return
slow, which is now the entrance of the cycle and therefore the repeated value.
Step-by-step example
nums = [1,3,4,2,2]
- The walk from index 0 goes 0, 1, 3, 2, 4, 2, 4 and so on, so the cycle is between 2 and 4 and its entrance is 2.
- Both pointers start at
nums[0] = 1. - First move:
slow = nums[1] = 3andfast = nums[nums[1]] = nums[3] = 2. They differ. - Second move:
slow = nums[3] = 2andfast = nums[nums[2]] = nums[4] = 2. They meet at 2. - Reset
slowtonums[0] = 1. Step both: slow goes to 3 and fast goes tonums[2] = 4. Step again: slow goes tonums[3] = 2and fast goes tonums[4] = 2. - They meet at 2, so the duplicate is 2.
Code: Python, Java, C++
1class Solution:
2 def findDuplicate(self, nums: List[int]) -> int:
3 # Phase 1: Find intersection point in cycle
4 slow = fast = nums[0]
5 while True:
6 slow = nums[slow]
7 fast = nums[nums[fast]]
8 if slow == fast:
9 break
10
11 # Phase 2: Find entrance to cycle (the duplicate)
12 slow = nums[0]
13 while slow != fast:
14 slow = nums[slow]
15 fast = nums[fast]
16
17 return slow1class Solution {
2 public int findDuplicate(int[] nums) {
3 // Phase 1: Find intersection point in cycle
4 int slow = nums[0];
5 int fast = nums[0];
6 do {
7 slow = nums[slow];
8 fast = nums[nums[fast]];
9 } while (slow != fast);
10
11 // Phase 2: Find entrance to cycle (the duplicate)
12 slow = nums[0];
13 while (slow != fast) {
14 slow = nums[slow];
15 fast = nums[fast];
16 }
17
18 return slow;
19 }
20}1class Solution {
2public:
3 int findDuplicate(vector<int>& nums) {
4 // Phase 1: Find intersection point in cycle
5 int slow = nums[0];
6 int fast = nums[0];
7 do {
8 slow = nums[slow];
9 fast = nums[nums[fast]];
10 } while (slow != fast);
11
12 // Phase 2: Find entrance to cycle (the duplicate)
13 slow = nums[0];
14 while (slow != fast) {
15 slow = nums[slow];
16 fast = nums[fast];
17 }
18
19 return slow;
20 }
21};Time and space complexity
O(n)
In the first phase the fast pointer gains one step per move on the slow one, so they meet within a number of moves bounded by the path length plus the cycle length, both at most n + 1. The second phase also takes at most that many moves.
O(1)
Only two integer pointers are used, and the array is only read, never written.
Other approaches
Binary search on the value range (time O(n log n), space O(1))
Guess a value mid and count how many elements are at most mid. If the count exceeds mid, the duplicate is at or below mid, otherwise it is above. This also meets the constant-space, read-only rules and is easier to prove, at the cost of a log factor.
Hash set (time O(n), space O(n))
Scan the array and return the first value already in the set. It is the fastest to write and runs in linear time, but it breaks the constant-space requirement.
Common mistakes
- Starting both pointers at index 0 and checking
slow == fastbefore moving, which makes the loop exit immediately. The code moves first and checks after, which is why it useswhile Truewith a break. - Resetting the slow pointer to 0 instead of
nums[0]in the second phase. Both phases must count steps from the same starting point, and here the first phase effectively started atnums[0]. - Returning the meeting point from the first phase. That is some node inside the cycle, not necessarily its entrance.
- Sorting the array or marking visited entries by negating them. Both modify the input, which the problem forbids.
Frequently asked questions
Why does Floyd's algorithm find the duplicate number?
Following i = nums[i] from index 0 forms a path that ends in a cycle. The cycle's entrance has two incoming edges, meaning two indices store the same value, so the entrance is the duplicate. Floyd's second phase lands exactly on that entrance.
Can you find the duplicate without extra space and without modifying the array?
Yes. Floyd's cycle detection does it in O(n) time with two pointers, and binary search over the value range does it in O(n log n) time. Both only read the array.
Why does the second phase meet at the cycle entrance?
If the path to the cycle has length a, the meeting point is placed so that walking a more steps from it also lands on the entrance. So a pointer from the start and a pointer from the meeting point, moving at the same speed, arrive at the entrance together.