Home > OS >  My code is failing a mysterious edge case
My code is failing a mysterious edge case

Time:07-24

I am working on Hackerrank's Migratory Birds problem.

Given an array of bird sightings where every element represents a bird type id, determine the id of the most frequently sighted type. If more than 1 type has been spotted that maximum amount, return the smallest of their ids.

My solution is as follows:

def migratoryBirds(arr):
    _dict = {}
    for key in arr:
        if key not in _dict:
            _dict[key] = 1
        else:
            _dict[key]  = 1
    _max_key = 0
    _max_cnt = 0
    for key in _dict:
        if _dict[key] > _max_cnt:
            _max_key = key
            _max_cnt = _dict[key]
    return _max_key

It is failing a single test case (case 4). Since it is really large, I can't paste it here. Could someone tell me what I am doing wrong?

CodePudding user response:

I found what the question is. It specifically states that in case of two birds having an equal count, you must return the one with the smallest id. There is no guarantee that you are iterating through the id's in increasing id order.

if _dict[key] > _max_cnt or (_dict[key] == _max_cnt and key < _max_key):

You could also improve your code using:

for key, value in _dict.items():

rather than fetching _dict[key] twice.

CodePudding user response:

Here's my solution, It should work

def migratory_birds(li):
    x = dict()
    for i in li:
        if i not in x.keys():
            x[i] = li.count(i)

    li = [k for k, v in x.items() if v == max(x.values())]

    return min(li)
  • Related