Skip to problem
←

Find the Duplicate Number

Easy 0 attempts

You're given an array nums holding n + 1 integers, each falling somewhere between 1 and n inclusive, and exactly one value is repeated in the array. Identify that repeated value, without modifying the array and using only O(1) extra space.

Edge cases: The same value could show up more than twice. The array is guaranteed to contain at least two elements.

Function contract

nums has n + 1 integers in [1, n]. Exactly one distinct value occurs more than once; it may occur more than twice.

Output: Return the repeated value, not an index. Do not modify nums; use O(1) auxiliary space.

Example 1

Input
nums = [1,3,4,2,2]
Output
2

Example 2

Input
nums = [2,2,2,2,2]
Output
2
Constraints
  • 1 <= n <= 10^5
  • nums.length == n + 1
  • 1 <= nums[i] <= n
  • Exactly one distinct value appears more than once; every other value appears at most once.

Approach: Floyd's Cycle Detection

Treat each value as a pointer to the next index. Because there's a duplicate, following these pointers creates a cycle — exactly like a linked list with a loop. Use a slow and fast pointer to detect the cycle, then find the entrance. Index 0 cannot belong to the cycle because no value points to 0. The cycle entrance has two incoming links on this walk, so its index is the duplicated value.

For [1,3,4,2,2], the index walk is 0 → 1 → 3 → 2 → 4 → 2 → …; the cycle starts at 2. Reset the slow pointer to index 0, then move both pointers one step at a time to find that entrance.

javascript
function findDuplicate(nums) {
  let slow = nums[0];
  let fast = nums[nums[0]];

  while (slow !== fast) {
    slow = nums[slow];
    fast = nums[nums[fast]];
  }

  slow = 0;
  while (slow !== fast) {
    slow = nums[slow];
    fast = nums[fast];
  }
  return slow;
}

Time Complexity: O(n)

Space Complexity: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript