Start learning free

LESSON 148 OF 314 · LINKED LISTS

Find the Duplicate Number in C++: Floyd's Cycle Detection in O(n)

Practice O(n) Read the full explanation

You get a vector nums of n + 1 whole numbers. Each number is from 1 to n.

One number appears more than once. Return that number.

Don't change nums. The tests check that it stays the same.

Use only a few extra variables. Don't copy nums, and don't keep an unordered_set of the numbers you have seen.

Why is this a linked list lesson? Think of each index as a node. Then nums[i] is the index of the next node.

 

Example 1:

Input: nums = [3,5,1,2,4,3]
Output: 3
Explanation: 3 appears at index 0 and at index 5.
As a linked list, the walk from index 0 goes:
0 -> 3 -> 2 -> 1 -> 5 -> 3 -> 2 -> ...
It goes around forever, and the loop starts at 3.

Example 2:

Input: nums = [4,2,4,4,1]
Output: 4
Explanation: 4 appears three times.
The number 3 does not appear at all.

Example 3:

Input: nums = [1,1]
Output: 1
Explanation: Here n is 1, so both numbers must be 1.

 

Constraints:

  • n is from 1 to 100,000.
  • nums has n + 1 numbers.
  • Each number is from 1 to n.
  • Exactly one number repeats, maybe many times.
  • Every other number appears at most once.
Note:

Your solution should run in O(n) time with O(1) extra memory.



Start at index 0 and follow the arrows: from index i, go to index nums[i]. No number is 0, so the walk never comes back to index 0. It has only n other indexes to visit, so it must run into a loop.

Two indexes hold the repeated number, so two arrows lead into it. That is where the loop starts. Find that index as in Linked List Cycle: a slow and a fast pointer meet inside the loop. Then put one pointer back at index 0. Move both one step at a time. They meet where the loop starts.

Each of the two walks takes at most a few times n steps: O(n) time.
Only two indexes are kept: O(1) extra memory.
Keeping an unordered_set of seen numbers also takes O(n) time, but it needs O(n) extra memory. Sorting would change nums.
STEP 1 OF 9
    Ctrl + Enter to check

    C++ · LINKED LISTS

    Find The Duplicate Number in C++, explained

    Problem overview

    The method findDuplicate gets a vector<int>& nums with n + 1 numbers, each between 1 and n. Exactly one number repeats (possibly many times), and every other number appears at most once. Return the repeated number.

    There are rules on top of that. nums must not change, the tests check that it stays the same. The extra memory must be O(1), so no copy of nums and no unordered_set of seen numbers. The time must be O(n).

    For [3,5,1,2,4,3] the answer is 3. For [4,2,4,4,1] it is 4 (it appears three times, and the value 3 is missing). For [1,1] it is 1.

    Approach: treat the vector as a linked list

    Read each index as a node, and let nums[i] be the index of the node that comes after node i. Start at index 0 and keep following the arrows. Two facts make this a cycle problem:

    • No value is 0, so no arrow points back to index 0. The walk from 0 can never return to its start.
    • Every value is between 1 and n, so the walk only visits indexes 1 to n, after leaving 0. With only n such indexes, it must repeat one, and then it loops forever.

    Where does the loop start? A node in a loop has an arrow coming from the previous node in the loop. The first node of the loop has a second arrow coming in from outside the loop, from the path that led to it. Two arrows into one node means two indexes holding the same value, which is the repeated number. So the loop starts at the duplicate.

    In [3,5,1,2,4,3] the walk from 0 goes 0, 3, 2, 1, 5, 3, 2, 1, 5 and so on. The loop is 3, 2, 1, 5 and it starts at 3, which is the repeated number: both index 0 and index 5 hold 3. In [4,2,4,4,1] the walk is 0, 4, 1, 2, 4, 1, 2, and the loop 4, 1, 2 starts at 4.

    Finding the start of a loop is Floyd's method, in two phases:

    1. Meet inside the loop. A slow pointer moves one step at a time and a fast pointer moves two. The walk never ends, so the fast pointer cannot fall off. Once both are in the loop, the fast one gains one step per round and catches the slow one.
    2. Find the start. Put the slow pointer back at index 0 and leave the fast one at the meeting point. Move both one step at a time. The distance from index 0 to the loop's start equals the distance from the meeting point forward to the same start (counted around the loop), so they arrive at the start together.

    Tracing the code on [3,5,1,2,4,3], the first phase goes through slow, fast = 3 and 2, then 2 and 5, then 1 and 2, then 5 and 5. They meet at index 5. After the reset, the second phase gives 3 and 3 after one round, so the answer is 3. For [4,2,4,4,1] the pointers start at 4 and 1, then 1 and 4, then meet at 2. In the second phase the first round gives 4 and 4, so the answer is 4.

    Each phase takes at most a few times n steps, which is O(n), and only two indexes are stored: O(1). The alternatives break a rule: a set of seen numbers needs O(n) memory, and sorting would change nums.

    Step by step

    1. Create slow as nums[0]: one step from index 0.
    2. Create fast as nums[nums[0]]: two steps from index 0.
    3. Loop while slow != fast.
    4. Move slow one step: slow = nums[slow].
    5. Move fast two steps: fast = nums[nums[fast]].
    6. After the loop, reset slow to 0 and leave fast at the meeting point.
    7. Second loop, again while slow != fast.
    8. Move both one step: slow = nums[slow] and fast = nums[fast].
    9. Return slow. It stands on the first node of the loop, which is the repeated number.

    The solution in C++

    class Solution {
    public:
        int findDuplicate(vector<int>& nums) {
            int slow = nums[0];
            int 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;
        }
    };
    

    The C++ details worth a closer look:

    • The pointers are ints. slow and fast hold indexes, not C++ pointers, and "following an arrow" is just nums[slow]. Every value is between 1 and n, and the vector has n + 1 entries, so each index read is valid.
    • Taking one step before the loop. Both pointers start one and two steps in, instead of at index 0. If they both started at 0, the condition slow != fast would be false at once and the first loop would never run. Starting ahead avoids that, and the phases still work.
    • nums is only read. Nothing writes to the vector, so the caller gets it back unchanged. Passing it as vector<int>& avoids a copy, and the function does not need to modify it.
    • The return value is a value, not an index. The loop's start is an index, but it is also the repeated number: the repeated value is the index that two arrows point to.

    Complexity

    Time is O(n): the first phase ends within a few passes of the path, and the second walks at most the distance to the loop start. Extra memory is O(1): two int variables.

    Edge cases and common mistakes

    • The smallest input. [1,1] has n = 1. Both pointers start at 1, so the first loop is skipped. After the reset, one round of the second loop gives 1 and 1, and the answer is 1.
    • A value repeated many times. [2,2,2,2,2] returns 2. The method does not assume the number appears just twice.
    • Returning the meeting point. After the first loop the pointers meet somewhere inside the loop, which is not necessarily the repeated number. In the first example they meet at 5, but the answer is 3. The second phase is needed.
    • Letting the second phase move fast by two steps. Both must move one step at a time.
    • Sorting or marking values in nums to find the duplicate. That changes the vector, which the tests do not allow.

    Testing

    The function returned these results, and [3,5,1,2,4,3] was unchanged afterwards:

    numsResult
    [3,5,1,2,4,3]3
    [4,2,4,4,1]4
    [1,1]1
    [2,2,2,2,2]2
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free