How I Solved Hacker Rank Challenge ‘Birthday Cake Candles’
Here is the challenge instructions:
You are in charge of the cake for a child’s birthday. You have decided the cake will have one candle for each year of their total age. They will only be able to blow out the tallest of the candles. Count how many candles are tallest.
Example:
candles = [4, 4, 1, 3]
The maximum height of the candles is 4 units high. There are 2 of them, so return 2. Here is how I solved the problem.
def birthdayCakeCandles(candles):
# Write your code here
max_num = max(candles)
count = 0
for candle in candles:
if candle == max_num:
count += 1
return count
I obtained the max candle height and set it to variable max_num. I also created a new variable to track the count and set it to zero.
I looped through the array of candle heights and incremented the count anytime the candle height matched the maximum height I already set.
Lastly, I returned the count.
This approach is efficient with a time complexity of O(n)
, where n
is the number of candles because both max()
and count()
functions iterate through the list once.