GeeksforGeeks » Algorithms

Element repeated thrice

(10 posts)

Tags:

  1. ANIRBAN GHOSH
    guest
    Posted 2 years ago #

    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?

  2. kartik
    Moderator
    Posted 2 years ago #

    Build a Hash Map of numbers as hash keys and count as hash values.
    Print the number with count as 3.

  3. kartik
    Moderator
    Posted 2 years ago #

    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)

  4. devendraiiit
    Member
    Posted 2 years ago #

    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)

  5. Gautham
    Member
    Posted 2 years ago #

    @devendraiit But what about the elements which are appear only once?

  6. devendraiiit
    Member
    Posted 2 years ago #

    @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

  7. Gautham
    Member
    Posted 2 years ago #

    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.

  8. kartik
    Moderator
    Posted 2 years ago #

    "repeated thrice" means element is appearing four times. Doing XOR of all elements won't result this element.

  9. ANIRBAN GHOSH
    guest
    Posted 2 years ago #

    Sorry, by repeated thrice I mean to say occurred 3 times exactly.

  10. RJ
    guest
    Posted 1 year ago #

    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.

RSS feed for this topic