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 ton, after leaving 0. With onlynsuch 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:
- 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.
- 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
- Create
slowasnums[0]: one step from index 0. - Create
fastasnums[nums[0]]: two steps from index 0. - Loop while
slow != fast. - Move
slowone step:slow = nums[slow]. - Move
fasttwo steps:fast = nums[nums[fast]]. - After the loop, reset
slowto 0 and leavefastat the meeting point. - Second loop, again while
slow != fast. - Move both one step:
slow = nums[slow]andfast = nums[fast]. - 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.
slowandfasthold indexes, not C++ pointers, and "following an arrow" is justnums[slow]. Every value is between 1 andn, and the vector hasn + 1entries, 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 != fastwould be false at once and the first loop would never run. Starting ahead avoids that, and the phases still work. numsis only read. Nothing writes to the vector, so the caller gets it back unchanged. Passing it asvector<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]hasn = 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
numsto 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:
| nums | Result |
|---|---|
[3,5,1,2,4,3] | 3 |
[4,2,4,4,1] | 4 |
[1,1] | 1 |
[2,2,2,2,2] | 2 |
