Cover image for LeetCode Hot 100 P287 Find the Duplicate Number

LeetCode Hot 100 P287 Find the Duplicate Number


Timeline

Timeline

2026-03-17

init

Two pointers, pigeonhole principle, Floyd's cycle detection (Floyd's tortoise and hare)

Problem:

The pigeonhole principle (also called the drawer principle) is a very basic but powerful principle in combinatorics.

Basic idea: If n+1 pigeons are placed into n holes, then at least one hole contains ≥2 pigeons.

This problem uses Floyd’s cycle detection, converting it into a problem like P142.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <vector>
using std::vector;

class Solution {
public:
int findDuplicate(vector<int> &nums)
{
// 1 <= n <= 105
// nums.length == n + 1
// 1 <= nums[i] <= n
// In nums, only one integer appears two or more times, and all other integers appear only once.

int slow = 0, fast = 0;

do {
slow = nums[slow];
fast = nums[nums[fast]];
} while (slow != fast);
// Meeting
slow = 0;
do {
slow = nums[slow];
fast = nums[fast];
} while (slow != fast);

return slow;
}
};