Find the Duplicate Number
Medium
Topics
Given an array nums of n+1 integers where each value is in [1, n], exactly one value is repeated. Return the repeated number without modifying the array and using O(1) extra space.
Example 1
Reading
i → nums[i] as a pointer makes the array a linked list, and a repeated value is a node with two things pointing at it — the entry to a cycle. The duplicate is 2.Cells are the array values; the small numbers underneath are indices.
Input: nums = [1,3,4,2,2] Output: 2
Example 2
Input: nums = [3,1,3,4,2] Output: 3
Constraints
- 1 <= n <= 10^5
- nums.length == n + 1
- Only one repeated number, but it may appear more than once.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Because values lie in [1, n], treat each value as a "next index" pointer. Following these pointers must eventually cycle, and the entrance to the cycle is the duplicate.
Floyd’s tortoise-and-hare finds that cycle entrance in O(1) space, without altering the array.
Approach
- Phase 1: advance
slowby one andfastby two until they meet inside the cycle. - Phase 2: reset
slowto the start; move both one step at a time. Where they meet is the cycle entrance = the duplicate.
Walkthrough
nums = [1,3,4,2,2]
follow indices -> a cycle forms at value 2
Floyd meeting + reset lands on 2 -> answer 2Complexity
- Time — O(n): both phases traverse a linear number of steps.
- Space — O(1): two pointers, array untouched.
Common Pitfalls
- Sorting or a hash set are simpler but violate the O(1)-space / read-only constraints.
Full Solution — all languages
class Solution:
def findDuplicate(self, nums):
slow = fast = nums[0]
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
slow = nums[0]
while slow != fast:
slow = nums[slow]
fast = nums[fast]
return slowimport java.util.*;
class Solution {
public int findDuplicate(int[] nums) {
int slow = nums[0], fast = nums[0];
do {
slow = nums[slow];
fast = nums[nums[fast]];
}
while (slow != fast);
slow = nums[0];
while (slow != fast) {
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int findDuplicate(vector<int>& nums) {
int slow = nums[0], fast = nums[0];
do {
slow = nums[slow];
fast = nums[nums[fast]];
}
while (slow != fast);
slow = nums[0];
while (slow != fast) {
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var findDuplicate = function(nums) {
let slow = nums[0], fast = nums[0];
do {
slow = nums[slow];
fast = nums[nums[fast]];
}
while (slow !== fast);
slow = nums[0];
while (slow !== fast) {
slow = nums[slow];
fast = nums[fast];
}
return slow;
};