2,206 views
2 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 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 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 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.

Position:
Show:

Related questions

0 0 votes
0 0 answers
314
314 views
Priya0612 asked Aug 23, 2018
314 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 0 votes
0 0 answers
586
586 views
Sahil_Lather asked Jan 28, 2023
586 views
Consider the following graph. If BFS is implemented on the following graph where the root node is 1 then which of the following set of the nodes are present in the queue ...
0 0 votes
0 0 answers
2.1k
2.1k views
Shubhanshu asked Oct 18, 2017
2,058 views
In a binary min heap with n elements, the 7th smallest element can be found in _____ ?Answer given is O(logn) and solution:-Delete the 1st smallest element O(logn)Delete ...
1 1 vote
1 1 answer
2.3k
2.3k views
iarnav asked Apr 28, 2017
2,287 views
Let's say we have an array of 5 elements.Array index starts from 0 Base address of Array = 100 size of each element is 2 ie it's an int arrayNow we want to find the 2nd e...