How I Solved Hacker Rank Challenge ‘Birthday Cake Candles’

Danielle Torres
1 min readJul 2, 2024

--

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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Danielle Torres
Danielle Torres

Written by Danielle Torres

Highly organized & motivated Software Engineer with an application analyst/data analyst background.

No responses yet

Write a response