</>

287. Find the Duplicate Number

Medium NeetCode 150
Linked List Time O(n) Space O(1)
↗ Open on LeetCode Source: Standard solution only

Quick review

Pattern
Linked List
Time
O(n)
Space
O(1)

Standard Solution (C++)

SummaryAn array of n+1 integers holds values in the range 1..n, so at least one value repeats. Identify the duplicate without modifying the array and using constant extra space.

Approach

Treat the array as a linked list where each value points to the index it names, then apply Floyd's cycle detection.

  • The duplicate value creates a cycle in this implicit list.
  • Phase one: advance a slow pointer one step and a fast pointer two steps until they meet.
  • Phase two: reset one pointer to the start and move both one step at a time; their meeting point is the duplicate.
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;
    }
};
Time O(n) Space O(1)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern