← DSA
MEDIUM

Find the Duplicate Number

PracticeNeetCode ↗LeetCode ↗

Given an array nums of n + 1 integers where every value lies in the range [1, n], exactly one value repeats (possibly more than twice). Find that duplicate without modifying the array and using only O(1) extra space.

Example

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

Key Pointers

Step-by-Step Analysis

  1. Initialize slow = nums[0], fast = nums[0].
  2. Phase 1: move slow = nums[slow] and fast = nums[nums[fast]] until slow == fast.
  3. Phase 2: reset slow = nums[0]; advance both slow and fast one step at a time until they meet again.
  4. That second meeting point is the duplicate — return it.

Complexity

Time: O(n) — Space: O(1)

Code

def findDuplicate(nums: list[int]) -> int:
    slow, fast = nums[0], 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 slow

Code Explanation

How the solution above works, piece by piece.

  1. Values are in 1..n and there are n + 1 of them, so following i → nums[i] from index 0 never leaves the array and must eventually loop.
  2. The duplicate value is the node two different indices point to, which is exactly where the path enters the loop.
  3. Phase 1 (like Linked List Cycle): slow takes one hop, fast two, until they meet somewhere in the loop.
  4. Phase 2: restart slow at the beginning and move both one hop at a time. The distance maths of Floyd's algorithm makes them meet exactly at the loop entry.
  5. O(n) time and O(1) space, without modifying the array.

Visual Walkthrough

Running it on nums = [1, 3, 4, 2, 2]:

Index graph i to nums[i] for 1 3 4 2 201324cycle entry = 2phase 1 meet: slow = fast = 2phase 2 from start meets at 2answer: 2
Treat each index as a node with an arrow to nums[i]. Two indices (3 and 4) both point to 2, so 2 is where the path enters a loop, and that entry node is the duplicate. Floyd's algorithm finds a meeting point in the loop, then the loop's entry.
duplicate / loop entrythe loop

Video Explanation

NeetCode — Floyd's Cycle Detection, LeetCode 287