75-days-dsa-challenge

Ninja technique🥷 to ACE DSA Interviews.

View the Project on GitHub

287. Find the Duplicate Number

There is only one repeated number in nums, return this repeated number.

You must solve the problem without modifying the array nums and uses only constant extra space.

O(N^2) Brute force

O(NlogN) Sorting

O(N) Time O(N) space, Hash Table

Floyd’s Cycle Detection Algorithm

class Solution{
public:
	int findDuplicate(vector<int> &nums){
		int slow = nums[0];
		int fast = nums[0];

		do{
			slow = nums[slow];
			fast = nums[nums[fast]];
		} while (slow != fast);

		fast = nums[0];
		while (slow != fast){
			slow = nums[slow];
			fast = nums[fast];
		}
		return slow;
	}
};