DEV Community

David
David

Posted on

How I Solved the HackerRank "Birthday Cake Candles" Problem in JS

I recently encountered a fun problem called "Birthday Cake Candles" on a coding challenge platform. The goal is straightforward: given an array representing the heights of candles, I need to figure out how many tallest candles there are. Here's how I approached the problem using JavaScript.

Problem Breakdown
We are given an array, ar, where each element represents the height of a candle. The task is to:

  • Find the tallest candle(s).

  • Count how many candles have that tallest height.

Solution Approach
I took a two-step approach to solving this problem:

  • First, I looped through the array to find the height of the tallest candle.

  • Then, I looped again to count how many candles are of that tallest height.

Here’s the JavaScript solution I came up with:

function birthdayCakeCandles(ar) {
    let tallestCandle = 0;
    let tallestCandlesCount = 0;

    // Step 1: Find the height of the tallest candle
    for (let i = 0; i < ar.length; i++) {
        if (ar[i] > tallestCandle) {
            tallestCandle = ar[i];
        }
    }

    // Step 2: Count how many candles have the tallest height
    for (let j = 0; j < ar.length; j++) {
        if (ar[j] === tallestCandle) {
            tallestCandlesCount++;
        }
    }

    return tallestCandlesCount;
}
Enter fullscreen mode Exit fullscreen mode

Step-by-Step Walkthrough

  1. Initialize Variables: I started by declaring two variables:
  • tallestCandle: Holds the height of the tallest candle we find.

  • tallestCandlesCount: Keeps track of how many candles match the tallest height.

  1. Find the Tallest Candle: I looped through the ar array with a for loop. As I iterate through each candle height:
  • If the current candle is taller than the value stored in tallestCandle, I update tallestCandle to reflect this new height.
  1. Count the Tallest Candles:
    After determining the height of the tallest candle, I loop through the array again. For each candle that matches the tallestCandle height, I increment the tallestCandlesCount variable.

  2. Return the Result:
    Finally, after counting all the tallest candles, I return the value of tallestCandlesCount.

Top comments (0)