From ac51c297c4fca25d6b6528e4468f374534d9ba47 Mon Sep 17 00:00:00 2001 From: Rishabh <61419244+rishabh-kothari@users.noreply.github.com> Date: Sun, 18 Oct 2020 13:46:50 +0530 Subject: [PATCH] Create Find the only duplicate element in array In the given problem an array is given with elements in range [1,n] where n= size of the array -1. In the array only single element is repeating two or more times. We find that duplicate element in o(n) time and using o(1) space by using cycle detection algorithm. --- Find the only duplicate element in array | 35 ++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Find the only duplicate element in array diff --git a/Find the only duplicate element in array b/Find the only duplicate element in array new file mode 100644 index 0000000..7fd1f6e --- /dev/null +++ b/Find the only duplicate element in array @@ -0,0 +1,35 @@ +#include +using namespace std; +#define ll long long + +ll findDuplicateElement(ll a[],ll n) +{ + ll i=a[0],j=a[0]; + do + { + i=a[i]; + j=a[a[j]]; + }while(i!=j); + + j=a[0]; + while(i!=j) + { + j=a[j]; + i=a[i]; + } + return i; +} + +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + ll n,i; + cin>>n; + ll a[n]; + for(i=0;i>a[i]; + + cout<