Find the Duplicate Number

Find the one repeated value in an array without changing it, by reading the array as a walk that ends in a loop.

You are given an array nums of n + 1 integers, and every integer is between 1 and n. Exactly one value appears more than once, perhaps two times, perhaps more. Return that value. The array must not be changed, and the extra memory must stay a fixed size, a few variables, however long the array is.

Example 1
Input: nums = [1, 3, 4, 2, 2]
Output: 2
Example 2
Input: nums = [3, 1, 3, 4, 2]
Output: 3
Solution

The Idea

Example 1 has five numbers, [1, 3, 4, 2, 2], but only the values 1 to 4 are allowed. Five places and four values: some value has to appear twice, and here it is 2, at indexes 3 and 4. Finding it would be easy if we could note down every value we see, or sort the array so equal values sit side by side. The problem rules out both.

So we need another way to look at the array. You may have played a treasure hunt, where each clue tells you where to find the next clue. Read the array the same way: each index is a place, and the value stored there says which index to visit next. Start at index 0. nums[0] is 1, so go to index 1. nums[1] is 3, so go to index 3. Then nums[3] is 2, nums[2] is 4, and nums[4] is 2 again.

Look at the picture below. The top row is the array. The bottom row is the walk: each circle is an index, and each arrow goes from an index to the value stored there.

The array [1, 3, 4, 2, 2] read as a walk: from each index, go to the index its value names. The walk goes 0, 1, 3, 2, 4 and then back to 2. Index 2 is the entrance of the loop, and two arrows lead into it, from indexes 3 and 4, which both hold 2.

The walk starts at 0, passes 1 and 3, and reaches 2. From 2 it goes to 4, from 4 back to 2, and then round 2, 4, 2, 4 forever. Can that be a coincidence of this example? No. Every value is between 1 and n, so every value is a valid index, and there is always a next place to go. With only n + 1 places, the walk must sooner or later come back to a place it has already visited, and from then on it repeats the same round.

That repeating round is called a loop (or cycle). The part of the walk before it is the tail, and the first index of the loop is its entrance. In the picture, the tail is 0, 1, 3, the loop is 2, 4, and the entrance is 2.

Now look at the two orange arrows into the entrance: one from index 3, the last index of the tail, and one from index 4, the last index of the loop. An arrow into 2 means "this index holds 2", so two arrows into 2 mean that 2 appears twice. The entrance is the duplicate.

Does the entrance always get an arrow from the tail? Yes, because the tail is never empty. No value is 0, so no arrow leads to index 0, and the walk never comes back to it. Index 0 is always on the tail.

So the question changes from "which value repeats?" to "where does the loop of this walk begin?" If you have met linked lists, where each item stores the address of the next item, this is the same picture, with indexes in place of addresses.

Solution Approach

Turning the walk into code means settling two things: how to tell that the walk has reached its loop, and how to then find the loop's entrance. First, though, why not use a simpler way?

The simple ways

What is wrong with checking each value in turn? Counting how often each value appears is correct and needs no extra memory, but it takes about n × n steps: 100 million for 10,000 numbers. A HashSet, a collection that answers "have I seen this value?" in one step, finds the duplicate in one pass, but it may hold up to n values. Sorting puts the copies side by side, but it changes the array. The walk needs none of these.

Meeting inside the loop

How can a marker know it is inside the loop, when it only ever sees one index? Send two markers along the walk from index 0: slow moves one step at a time, and fast moves two. On the tail, fast pulls ahead. Once both are in the loop, it is like two runners on a track. fast gains one step with every move, so the gap between them shrinks by one each time until it is zero.

In Example 1, after each move slow is at 1, 3, 2, 4 and fast at 3, 4, 4, 4. They meet at index 4 after four moves. That is inside the loop, but it is not the entrance.

Finding the entrance

How do we get from the meeting index, 4, to the entrance, 2? By counting steps. Say the tail takes a steps to reach the entrance, and one round of the loop takes c steps. In Example 1, a is 3 (0 to 1, 1 to 3, 3 to 2) and c is 2.

When the markers met, slow had made k moves and fast twice as many. They stood on the same index, so the extra k steps of fast were whole rounds of the loop. In Example 1, k is 4, two rounds of 2 steps.

Now put slow back on index 0 and move both markers one step at a time. After a moves, slow is at the entrance. fast started where the walk is after k steps, so it is now where the walk is after a + k steps: at the entrance, plus some whole rounds. So both markers reach the entrance on the same move. They cannot meet sooner, because until then slow is on the tail and fast is in the loop.

In Example 1, slow goes 1, 3, 2 and fast goes 2, 4, 2. They meet at 2 after three moves, which is a. This two-part search is known as Floyd's cycle detection, and Linked List Cycle II uses it on a real linked list.

Java Solution

The method findDuplicate works in these steps:

  1. First, place two markers, the int variables slow and fast, on index 0.
  2. In a do-while loop, move slow one step with slow = nums[slow] and fast two steps with fast = nums[nums[fast]]. Stop when they are equal.
  3. Put slow back on index 0. In a second, plain while loop, move both markers one step at a time until they are equal again.
  4. Return slow: it is the entrance of the loop, which is the repeated value.

The main method runs both examples, printing the first array again afterwards. Then it tries [1, 1], the smallest input, [2, 2, 2, 2, 2], and [4, 1, 4, 2, 4], where 4 appears three times.

Java
import java.util.Arrays;

public class FindTheDuplicateNumber {

    public static int findDuplicate(int[] nums) {
        int slow = 0;
        int fast = 0;
        do {
            slow = nums[slow];               // one step
            fast = nums[nums[fast]];         // two steps
        } while (slow != fast);              // they meet somewhere inside the loop

        slow = 0;                            // back to the start of the walk
        while (slow != fast) {
            slow = nums[slow];               // both one step now
            fast = nums[fast];
        }
        return slow;                         // the loop entrance: the repeated value
    }

    public static void main(String[] args) {
        int[] nums = {1, 3, 4, 2, 2};
        System.out.println(findDuplicate(nums) + "  array after: " + Arrays.toString(nums));
        System.out.println(findDuplicate(new int[] {3, 1, 3, 4, 2}));
        System.out.println(findDuplicate(new int[] {1, 1}));
        System.out.println(findDuplicate(new int[] {2, 2, 2, 2, 2}));
        System.out.println(findDuplicate(new int[] {4, 1, 4, 2, 4}));
    }
}

Running it prints:

Output
2  array after: [1, 3, 4, 2, 2]
3
1
2
4

Look at the first line: the answer to Example 1 is 2, and the array printed next to it is still [1, 3, 4, 2, 2], because the method only reads it. The 3 below it answers Example 2, where the walk 0, 3, 4, 2, 3 has a tail of one step and a loop of three indexes.

The 1 comes from [1, 1]. Index 0 holds 1 and index 1 holds 1, so the walk goes 0, 1, 1, 1, and the loop is the single index 1. In [2, 2, 2, 2, 2] the walk goes 0, 2, 2, and indexes 1, 3 and 4 are never visited, yet the answer, 2, is still right. The last line, 4, shows that a value appearing three times is found the same way.

Why a do-while and not a plain while for the first part? Both markers start on index 0, so they are equal before the first move. A plain while would never run, the second while would also stop at once, and the method would return 0. A version written that way returns 0 for both examples.

Complexity

The work is the two rounds of moving the markers, and neither can last longer than the walk has indexes.

  • Time: O(n), where n + 1 is the length of the array. The tail and the loop together have at most n + 1 indexes. In the do-while, fast catches slow within one round after slow enters the loop, so slow makes at most n + 1 moves. The second while makes a moves, the length of the tail.
  • Space: O(1). The method keeps two int markers, and the array is only read, never copied or changed.