Dec 30, 2008

Given a read only array of size n each of which is a number between 1 to n-1 inclusive, find any element which is present more than once in the array

Given a read only array of size n each of which is a number between 1 to n-1 inclusive, find any element which is present more than once in the array in linear time and constant space. E.g. 2 1 2 3 5 3. Output: 2 or 3

The index of array is from 0~n-1
The value in array is from 1~n-1
Suppose the array is 2,1,4,3,5,3
int idx=0;
while(1)
{
idx=a[idx];
cout<<idx;
}
So we will get sequence like: 2, 4,5,3,3,3,3,3…
From above we can know a loop which is in the array.
So we use two pointers, one is slow, one is quick to detect the loop
int f(int* a)
{
int Slow=0;
int fast=0;
do{
slow=a[slow];
fast=a[a[fast]];
}while(slow!=fast);
//Then we detect the length of loop
slow=a[slow];
int len=1;
while(slow!=fast)
{
len++;
slow=a[slow];
}
//find the duplicate number
slow=fast=0;
while(len--)
{
fast=a[fast];
}
while(slow!=fast)
{
slow=a[slow];
fast=a[fast];
}
}

No comments:

Post a Comment