Birthday Cake Candles - HackerRank Problem Solving

Featured image

Birthday Cake Candles is a Hackerrank problem from Algorithms subdomain that requires the understanding of loops. In this post, you will learn how to solve Hackerrank’s Birthday Cake Candles problem and its solution in Python and C++.

Problem Statement and Explanation

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.

In other words, find the number of occurrences of the maximum element in the array.

Example: 4 4 1 3

Input Format

Output Format

Birthday Cake Candles Solution in Python

Explanation of Solution in Python

birthdayCakeCandles(), which takes an array of integers (representing the heights of the candles on a birthday cake) as input and returns the number of candles that the birthday person can blow out.

The function works by first initializing a variable count to 0. Then, it finds the tallest candle in the array by using the max() function.

Next, the function iterates over the array and increments count each time it finds a candle that has the same height as the tallest candle.

Finally, the function returns the value of count, which is the number of candles that the birthday person can blow out.

Birthday Cake Candles Solution in C++

Explanation of Solution in C++

birthdayCakeCandles(), which takes an array of integers (representing the heights of the candles on a birthday cake) as input and returns the number of candles that the birthday person can blow out.

The function works by first initializing two variables: max and count. max will store the height of the tallest candle, and count will store the number of candles that have the same height as the tallest candle.

The function then iterates over the input array and compares each element to max. If the current element is greater than max, then the function updates max to be equal to the current element.

After the loop has finished iterating, the function iterates over the input array again and compares each element to max. If the current element is equal to max, then the function increments count.

Finally, the function returns the value of count, which is the number of candles that the birthday person can blow out.