Find the Duplicate Number
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Note: You must not modify the array (assume the array is read only). You must use only constant, O(1) extra space. Your runtime complexity should be less than O(n2). There is only one duplicate number in the array, but it could be repeated more than once.
https://leetcode.com/problems/find-the-duplicate-number/
Solution:
This approach essentially creates a graph out of the array (outgoing edge from each array value to the index denoted by that array value). Then, you run Floyd's cycle finding algorithm (tortoise and hare) to find the cycle (duplicate value in array). Look up Floyd's cycle finding algorithm for more info!
Simialr to find cycle in linkedList; i.e: 1 2 3 4 2
LinkedList: 0 -> 1 -> 2 -> 3 -> 4 -> 2
So cycle starts at 2, meaning 2 is the duplicate value
public class Solution {
public int findDuplicate(int[] nums) {
if (nums == null || nums.length <= 1) {
return -1;
}
int slow = 0;
int fast = 0;
int finder = 0;
while (true)
{
slow = nums[slow];
fast = nums[nums[fast]];
if (slow == fast)
break;
}
while (true)
{
slow = nums[slow];
finder = nums[finder];
if (slow == finder)
return slow;
}
}
}