GeeksforGeeks » Algorithms
Element repeated thrice
(10 posts)-
There is an array of N elements in which only one element is repeated thrice and all other elements repeated twice or did not repeat. Can the element that repeated thrice be found in O(N) time and constant space?
-
Build a Hash Map of numbers as hash keys and count as hash values.
Print the number with count as 3. -
Here is another trivial solution.
1) Sort the elements O(nLogn)
2) Traverse the sorted array and find out the element repeated thrice. O(n) -
Take Xor of all array elements in O(n) and it will give the number who has repeated thrice.
:) time O(n) space O(1)
-
@devendraiit But what about the elements which are appear only once?
-
@Gautham The question was mentioned as follows "only one element is repeated thrice and all other elements repeated twice or did not repeat."
So there would be no element appears once
-
Ok. When author posted "all other elements repeated twice or did not repeat" I thought elements can occur once too. My bad. Nice solution by the way.
-
"repeated thrice" means element is appearing four times. Doing XOR of all elements won't result this element.
-
Sorry, by repeated thrice I mean to say occurred 3 times exactly.
-
What if few elements are once few repeated twice and only one repeated thrice, find one which is repeated thrice?
Reply
You must log in to post.