forked from k-samarth/Data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTortoiseHare.cpp
More file actions
40 lines (33 loc) · 780 Bytes
/
Copy pathTortoiseHare.cpp
File metadata and controls
40 lines (33 loc) · 780 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//This code will find the duplicate number in an array using space complexity of O(1)
#include <bits/stdc++.h>
using namespace std;
int duplicate(vector<int>&arr){
int tortoise = arr[0];
int hare = arr[0];
//tortise moves one step
//hare moves two steps
do{
tortoise = arr[tortoise];
hare=arr[arr[hare]];
}while(tortoise!=hare);
//bring hare to the initial position
hare=arr[0];
//move both hare and tortoise one step
while(tortoise!=hare){
tortoise=arr[tortoise];
hare=arr[hare];
}
return tortoise;
}
int main()
{
int n,temp;
cin>>n;
vector<int>arr;
for(int i=0;i<n;i++){
cin>>temp;
arr.push_back(temp);
}
cout<<duplicate(arr);
return 0;
}