GeeksforGeeks » Algorithms
First repeating element
(4 posts)-
Given an array of n numbers in which all the members are less than or equal to k (k<n). device an algorithm of order O(k) to find the first repeating element.
-
Please see http://geeksforgeeks.org/?p=1781. Since the range is given in your question also, you can easily modify the code for integers.
-
Assuming that all numbers are positive (may include 0) then its simple:
iterate through the array and increase the count of the element appearing till you get all 1s, as soon as you get 2 return that same element.
Since there are only k distinct elements, then at worst case you will have to traverse k+1 times which is again O(k). -
#include<stdio.h> #define N 15 #define K 9 //elements lie between 0 to 9 int *init_count(int *); int index_first_non_repeating(int *); int main() { int a[] = {0,1,2,1,2,3,4,5,3,7,8,9,9,6,0}; // array has N elements int i = index_first_non_repeating(a); printf("First non-repeating integer in array is: %d\n",i); printf("Element at that index is is: %d\n",a[i]); return 0; } int index_first_non_repeating(int *a) { int *b = init_count(a); int i; for(i=0;i<N;i++) { if(b[a[i]] == 1) return i; } return -1; } int *init_count(int *a) { int *b = (int *)calloc(sizeof(int),(K+1)); int i; for(i=0;i<N;i++) b[a[i]]++; return b; }
Reply
You must log in to post.