LeetCode-Grind icon indicating copy to clipboard operation
LeetCode-Grind copied to clipboard

Sep19 2023 - Find-the-duplicate-number

Open Nabil-Salah opened this issue 1 year ago • 1 comments

Description

https://leetcode.com/problems/find-the-duplicate-number/?envType=daily-question&envId=2023-09-19

Code of Conduct

Nabil-Salah avatar Feb 10 '24 16:02 Nabil-Salah

class Solution {
public:
    int findDuplicate(vector<int>& nums) {
        ios_base::sync_with_stdio(false);
        cin.tie(0);
        cout.tie(0);

        int tortoise = nums[0];
        int hare = nums[0];

        // Phase 1: Find the intersection point of the two pointers
        do {
            tortoise = nums[tortoise];
            hare = nums[nums[hare]];
        } while (tortoise != hare);

        // Phase 2: Find the entrance of the cycle
        tortoise = nums[0];
        while (tortoise != hare) {
            tortoise = nums[tortoise];
            hare = nums[hare];
        }

        return hare;
    }
};

bitsgorilla avatar Jun 12 '24 10:06 bitsgorilla