Given an array containing n+1
elements wherein each element is between 1
and n
(inclusive), at least one number is duplicated. My target is to find the duplicate one. Note that this single number can be repeated more than once.
I found the following highly upvoted code. While I understand how and why it works, I am seeking an intuitive explanation:
class Solution {
public:
int findDuplicate(vector<int>& nums) {
if(nums.empty())
return -1;
int slow=nums[0];
int fast=nums[nums[0]];
while(slow!=fast) {
slow=nums[slow];
fast=nums[nums[fast]];
}
fast=0;
while(slow!=fast) {
slow=nums[slow];
fast=nums[fast];
}
return fast;
}
};
Question link: https://leetcode.com/problems/find-the-duplicate-number/description/
Using a pencil and paper, I could understand how the two pointers move about and finally rest on the single duplicate number. But how does it intuitively work?
Edit: Link to the highly upvoted solution: https://discuss.leetcode.com/topic/25913/my-easy-understood-solution-with-o-n-time-and-o-1-space-without-modifying-the-array-with-clear-explanation