1

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

  • https://www.youtube.com/watch?v=FkBm3NeWqak Hope this helps ..its a slight modification..For your problem cycle starts where there is a duplicate ..we are just interested in thta – Hariom Singh Oct 06 '17 at 03:02
  • Possible duplicate of [Explain how finding cycle start node in cycle linked list work?](https://stackoverflow.com/questions/2936213/explain-how-finding-cycle-start-node-in-cycle-linked-list-work) – Raymond Chen Oct 06 '17 at 03:15

0 Answers0