GeeksforGeeks » Algorithms

Check repitition of number in an Array

(6 posts)
  1. Vikrant
    guest
    Posted 7 months ago #

    Given an array , say abc[10]..
    10 numbers are entered by user..
    only one number is repeated..
    we have to output that repeated number...
    Please help me out in finding a nice algorithm for this.

  2. devan
    Member
    Posted 7 months ago #

    Declare another array Hash[], and do the following steps.
    i from 1 to 10 of abc,
    {
    if (Hash[abc[i]]==0) Hash[abc[i]]+=1;
    else abc[i] is the answer.
    }

  3. j
    Member
    Posted 7 months ago #

    if 'n' = number of first n natural numbers , then the repeated number can be found as

    sum of n numbers(with the repated number) - sum of first(n-1) numbers = repeated number

    eg: if n =5 then a[5] will have 4 natural numbers = 0,1,2,3,4. Lets say 3 is repeated. then:
    the input array has values : 1,2,3,3,4 , then applying the above algo will give:
    (1+2+3+4+3) - (sum of first 4 natural numbers(given n=5))
    => 13-10 = 3
    3 is the repeated number.

    you can try with any value of n.

    This applies only if the n is a sequence of n natural numbers. Let me know if the question is quoted otherwise.
    Thanks

  4. Vikrant
    guest
    Posted 7 months ago #

    thanx to all of you !!! :)

  5. Manu
    guest
    Posted 6 months ago #

    @devan: what would be size of Hash[] array??

  6. Saurya
    guest
    Posted 6 months ago #

    If there is no relation between the numbers (like not being consecutive), then sort the array(n log n) and then do a traverse through the array O( n).


Reply

You must log in to post.

RSS feed for this topic