Find the Duplicate Number

Pattern: Cyclic sort

medium

The array must not change, so do not swap. Read each value as an arrow to an index. The arrows from index 0 run into a cycle, and the repeated value is where the cycle begins. Floyd's slow and fast pointers find it.

The problem

You are given an array of n + 1 numbers, each from 1 to n. Exactly one value appears more than once (it may appear many times). Return that value without changing the array, using only O(1) extra memory. For example, [1, 3, 4, 2, 2] gives 2, and [3, 3, 3, 3, 3] gives 3.

The function name findDuplicate matches LeetCode. Use the link above for the exact statement and limits.

Think first

  • Cyclic sort would find it, but it changes the array. What else can a value in the range 1 to n be used for?
  • Draw an arrow from each index i to index nums[i]. What does the walk from index 0 eventually do?
  • Where does the walk first come back to a place it has already been?

Hints

    Brute force, and why it fails

    Compare every pair: O(n²). Sorting a copy, or a hash set, uses O(n) memory. Binary search on the value range (count how many values are at most mid) is O(n log n) with O(1) memory. Floyd's method is O(n) time and O(1) memory.

    The key insight

    Treating values as arrows turns "find the repeated value" into "find where a linked list's cycle begins". Floyd's two-speed walk answers that without writing anything.

    Dry run

    10 
    31 
    42 
    23 
    24 
    path0 1 3 2 4 2 4

    nums = [1, 3, 4, 2, 2]. Read index i as pointing to index nums[i]. From 0 the path is 0, 1, 3, 2, 4, 2, 4, and so on. It loops through 2 and 4.

    Step 1 of 4

    The plan

    slow = nums[0], fast = nums[0]
    repeat:
        slow = nums[slow]
        fast = nums[nums[fast]]
    until slow == fast
    slow = nums[0]
    while slow != fast:
        slow = nums[slow]
        fast = nums[fast]
    return slow
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    The walk reaches the cycle within n steps, and the pointers meet within one more lap. Only two indexes are stored.

    Edge cases

    • The smallest case, [1, 1]: 1.
    • The value repeated many times, as in [3, 3, 3, 3, 3]: still found.
    • The repeated value far from the front: the walk still reaches it.
    I've built my logic, show the code

    Java

    class Solution {
        public int findDuplicate(int[] nums) {
            // read each value as a pointer to an index: the repeated value is where the cycle starts
            int slow = nums[0], fast = nums[0];
            do {
                slow = nums[slow];                  // one step
                fast = nums[nums[fast]];            // two steps
            } while (slow != fast);
            slow = nums[0];                         // restart one walker; equal speeds now meet at the entrance
            while (slow != fast) {
                slow = nums[slow];
                fast = nums[fast];
            }
            return slow;
        }
    }

    C++

    class Solution {
    public:
        int findDuplicate(vector<int>& nums) {
            // read each value as a pointer to an index: the repeated value is where the cycle starts
            int slow = nums[0], fast = nums[0];
            do {
                slow = nums[slow];                  // one step
                fast = nums[nums[fast]];            // two steps
            } while (slow != fast);
            slow = nums[0];                         // restart one walker; equal speeds now meet at the entrance
            while (slow != fast) {
                slow = nums[slow];
                fast = nums[fast];
            }
            return slow;
        }
    };

    Python

    class Solution:
        def findDuplicate(self, nums: list[int]) -> int:
            # read each value as a pointer to an index: the repeated value is where the cycle starts
            slow = fast = nums[0]
            while True:
                slow = nums[slow]                   # one step
                fast = nums[nums[fast]]             # two steps
                if slow == fast:
                    break
            slow = nums[0]                          # restart one walker; equal speeds now meet at the entrance
            while slow != fast:
                slow = nums[slow]
                fast = nums[fast]
            return slow

    Common mistakes

    • Sorting or swapping in place, which the problem forbids.
    • Restarting slow at index 0 and fast at the meeting point, but moving them unevenly. In the second phase, both move one step.
    • Using a while slow != fast loop for the first phase. Both start equal, so it would stop at once. Move first, then compare.

    Similar problems