Top-20 Training Program (Data Structures) Array Example: 1) First Solution (Bruteforce)
Top-20 Training Program (Data Structures) Array Example: 1) First Solution (Bruteforce)
(Data Structures)
Array Example
Given an array of n integers in which each element is between 1 and n-1,
write an efficient function to determine any duplicated integer. You may
destroy the array. What are the time and space complexities of your
solution?
Function Prototype:
int findDuplicate(int a[], int n)
1) First Solution(BruteForce)
int findDuplicate(int a[ ], int n) {
int i, j;
for(i=0; i<n; i++) {
for(j=0; j<n; j++)
if(i!=j && a[i] == a[j]) return a[i];
}
return -1; //never be executed
}
2) Second Solution(Using Auxiliary Array)
int findDuplicate(int a[ ], int n) {
int i, *aux = calloc(n,sizeof(int)); //create bit array for more efficient storage
for(i=0; i<n; i++) {
if(aux[a[i]]) return a[i];
else aux[i] = 1;
}
return -1; //never be executed
}
www.algorithmica.co.in
Ph: +91-9246582537
www.algorithmica.co.in
Ph: +91-9246582537