GeeksforGeeks » Interview Questions
Interview Question about Algorithms
(7 posts)-
Find the second non repeating element in an array.
-
@Shekhu, one could use a hash map (with or without buckets) to find the second non repeating element in an array. Otherwise, one could use a unique key, value binary search tree. Thank you, Camster
-
int *a;// array
int find_second_non(int *a,int n)
for(int i=0;i<n-1;i++)
{ if(a[i]==a[i+1]&&i<n-1)
i++if(i<n)
return i;
else
return -1;
} -
@PINTUGUPTAJUIT , Your program does not compile and even after I fix the compilation mistakes it returns the wrong result,
Example 1
int a[] = {1, 6, 5, 6, 10, 9 , 4, 4};int a[] = {1, 6, 6, 5, 10, 9 , 4, 4};
Please correct it. Thank you,camster.
-
@PINTUGUPTAJUIT, Here is a O(N) time complexity O(1) space complexity program that that finds the second non repeating number in an array. Please correct it if you wish.Thank you Camster
test cases
int a[] = {9, 9, 9, 9, 9 , 4, 4, 1};
int a[] = {5, 4, 4, 6, 10, 9 , 4, 4};
int a[] = {1, 6, 5, 6, 10, 9 , 4, 4};
int n = 8;void findsecondnonrepeating(int a[], int n){ // use two pointers to traverse the array in O(N) time
int pointer1 = 0;
int pointer2 = 1;while (pointer1 < (n - 1) && pointer2 > pointer1){
if (pointer2 + 1 <= (n - 1)
&&
a[pointer1] != a[pointer2]
&&
a[pointer2] != a[pointer2 + 1]){
printf("candidate1 = %d\n",a[pointer2]);
break;
}
else if (a[pointer1] == a[pointer2]){
pointer1 += 2;
pointer2 += 2;
}
else if (pointer2 + 1 <= (n - 1)
&&
a[pointer1] != a[pointer2]
&&
a[pointer2] == a[pointer2 + 1]){
pointer2 += 2;
}
else if (pointer2 == (n-1)
&&
a[pointer1] != a[pointer2]){
printf("candidate2 = %d\n",a[pointer2]);
break;
}
else {
printf("IMPOSSIBLE = %d\n",pointer2);
break;
}
}
} -
//max , min are maximum and minimum elements in the arr for(i=0;i<n;i++) c[arr[i]]-min|++; } cnt=0; for(i=0;i<max;i++) { if(c[arr[i]-min]=1) { cnt++; } if(cnt==2) { break; } } -
@camster : please provide some explanation of your algo..it difficult to understand without comments in it.
thanks
Reply
You must log in to post.