Wednesday, February 16, 2011

Element that appears p% of times

You are given an array A of non unique elements and size M. Find an element that appears p% of times.

2 comments:

  1. p% times ..question is not clear can U provide the algo or code for this

    ReplyDelete
  2. def appears(a, p):
        m = len(a)
        count = {}
        for i in a:
            if count.has_key(i):
                count[i] += 1
            else:
                count[i] = 1
        for i, c in count.iteritems():
            if float(c)*100/m == p:
                return i
        return None

    a = [1,2,4,4,4,1,8,-1,23,23]
    print appears(a, 10)

    ReplyDelete