Find the Duplicate Number (LeetCode 287): Solution and Explanation

Medium
Array
Two Pointers
Binary Search
Bit Manipulation

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Set both slow and fast to nums[0], one step into the walk from index 0.
  2. Repeatedly move slow = nums[slow] and fast = nums[nums[fast]] until the two are equal. This is a meeting point inside the cycle.
  3. Reset slow = nums[0] while leaving fast at the meeting point.
  4. Move both one step at a time with slow = nums[slow] and fast = nums[fast] until they are equal.
  5. 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]
  1. 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.
  2. Both pointers start at nums[0] = 1.
  3. First move: slow = nums[1] = 3 and fast = nums[nums[1]] = nums[3] = 2. They differ.
  4. Second move: slow = nums[3] = 2 and fast = nums[nums[2]] = nums[4] = 2. They meet at 2.
  5. Reset slow to nums[0] = 1. Step both: slow goes to 3 and fast goes to nums[2] = 4. Step again: slow goes to nums[3] = 2 and fast goes to nums[4] = 2.
  6. 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 slow

Time and space complexity

Time

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.

Space

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 == fast before moving, which makes the loop exit immediately. The code moves first and checks after, which is why it uses while True with 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 at nums[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.