1,051 views
2 votes
2 votes

given an array of n element, what will be the time complexity to find 1st repeated element when array have more than one repeated elements??

3 Answers

0 votes
0 votes

$O(n)$

Algorithm:

int count(int a[],int n){
    int count[10];
    for i=1 to 10:
        count[i]=0;
    for  i = 1 to n{
        k = count[a[i]]++;
        if (k>1) 
            return  a[i];
    } 
    return 0;
}
0 votes
0 votes
It will be O(n)

Insert one by one each element in a hash table and whenever first collision will occur that key or element will be the first one to repeat. Since it can go upto n elements.. So O(n).. Space complexity O(n).
0 votes
0 votes

From a theoretical point of view, it will take $O(n \log n)$ time in the worst case. It can be done by sorting the array and then sequentially searching for any adjacent elements that are equal.

Note: The problem doesn't mention any bound on the elements of the array. The elements can be as large as wanted, and need not be integers! Assuming that the elements are bounded (as in Saurav's answer) or that the elements hash to unique locations (as in Sonu's answer) completely changes the problem.


Practically, you will always have a bound on the elements. If the bound is sufficiently small ($<32$ bits, for example), Saurav's answer will be efficient (if the $n\gg2^{32}$). Or you could have a hash function that provides unique hashes for all practical purposes. Then Sonu's answer would be the better way to go.

Related questions

0 votes
0 votes
0 answers
1
Priya0612 asked Aug 23, 2018
147 views
#include <stdio.h int main(void) { char a[5] = { 1, 2, 3, 4, 5 }; char *ptr = (char*)(&a + 1); printf("%d %d\n", *(a + 1), *(ptr - 1)); return 0; }what is o/p of this pro...
0 votes
0 votes
0 answers
2