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
Example 1
Output: 2
Example 2
Output: 3
The Idea
Example 1 has five numbers, [1, 3, 4, 2, 2]
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]nums[1]nums[3]nums[2]nums[4]
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 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
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: slowfastfastfast
In Example 1, after each move slowfast
Finding the entrance
How do we get from the meeting index, 4, to the entrance, 2? By counting steps. Say the tail takes acac
When the markers met, slowkfastkfastk
Now put slowaslowfastkakslowfast
In Example 1, slowfasta
Java Solution
The method findDuplicate
- First, place two markers, the
variablesint andslow , on index 0.fast - In a
-do loop, movewhile one step withslow andslow = nums[slow] two steps withfast . Stop when they are equal.fast = nums[nums[fast]] - Put
back on index 0. In a second, plainslow loop, move both markers one step at a time until they are equal again.while - Return
: it is the entrance of the loop, which is the repeated value.slow
The main[1, 1][2, 2, 2, 2, 2][4, 1, 4, 2, 4]
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:
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]
The 1 comes from [1, 1][2, 2, 2, 2, 2]
Why a dowhilewhilewhilewhile
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 catchesfast within one round afterslow enters the loop, soslow makes at most n + 1 moves. The secondslow makeswhile moves, the length of the tail.a - Space: O(1). The method keeps two
markers, and the array is only read, never copied or changed.int