Hackerrank Birthday Cake (I Almost Got but Something Wrong)

For example, if your niece is turning 4 years old, and the cake will have 4 candles of height 4, 4, 1, 3, she will be able to blow out 2 candles successfully, since the tallest candles are of height 4 and there are such 2 candles.

Sample Input

4

3 2 1 3

Sample Output

2

Here's my code

def birthdayCakeCandles(ar):
    candle = []

    for i in ar:
        if ar[i] == max(ar):
            candle.append(ar[i])

    print(len(candle))

In Pycharm, there's something trouble in """if[i] == max(ar)""" It says index error but I don't know why it causes index error..

2

1 Answer

You are confusing two concepts on how to iterate through a list. Also we don't need a list, we just need a variable candles which keeps count of number of valid candles

The first way is to pick each element in the list and use it, we do it by doing for elem in list, where elem=4,4,1..

def birthdayCakeCandles(ar):
    candles = 0
    #Maximum value in array
    max_arr = max(ar)
    #a in an element in ar
    for a in ar:
        if a == max_arr:
            candles+=1

    print(candles)

The second method is to get the indexes of the list and use those indexes to iterate, i.e. for i in range(len(ar)) where i=0,1,2... etc.

def birthdayCakeCandles(ar):
    candles = 0

    max_arr = max(ar)
    #i is the index in ar
    for i in range(len(ar)):
        if ar[i] == max_arr:
            candles+=1

    print(candles)

In both cases, the output is 2

7

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest