A Sweet Treat: Birthday Candles Challenge on HackerRank

Welcome to my first post ever on this platform! šŸ˜„

I'm stuck on a problem and can't seem to figure it out. Here's the link to the challenge: .

Most of my tests are passing, except for the last one.

Another user posted a similar question but with a different approach, and they're facing the same issue with the test case. Here's the link to their question: Birthday cake candles- hackerrank.

Below is the code I'm currently using:

function birthdayCakeCandles(ar) {
  ar = ar.sort();
  let high = [];
  for(let i = 0; i < ar.length; i++){
    if (ar[i] === ar[ar.length -1]){
      high.push(ar[i]);
    }
  }
  return high.length;
}

Would really appreciate any help or suggestions. Thank you! šŸ™

Answer ā„–1

After reviewing your code, it seems to be correct!

For better optimization, consider storing the highest value as a variable to avoid calculating it during each iteration. Also, instead of storing the entire array, you can just store the count of the tallest candles in a variable like high.

function birthdayCakeCandles(ar) {
    ar = ar.sort();
    let highest = ar[ar.length-1] //calculate once only
    let high = 0;
    for(let candle of ar){
        if (candle === highest){
            high ++; //incrementing
        }
    }
    return high;
}

birthdayCakeCandles([1,2,3,4,5,3,2,5,4,1,2]) //2

Another approach is to use the indexOf method.

function birthdayCakeCandles(ar) {
    ar = ar.sort();
    let highest = ar[ar.length-1]
    return ar.length - ar.indexOf(highest);
}
birthdayCakeCandles([1,2,3,3,2,1,5,5,6,4,6,4,3,2,2,2,2]) //2

Edit: It seems that some input cases are not working due to the Array.sort() function sorting the array alphabetically. This can be resolved by passing a function to the sort() method to handle items numerically. Refer to developer.mozilla.org for more information.

numbers.sort(function(a, b) {
  return a - b;
})

To simplify, you can use an arrow function.

numbers.sort((a, b) => a - b)

Replace all instances of ar.sort() with ar.sort((a, b) => a - b)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you explain the significance of the res.render callback parameter in Express 4.0 for Node.js?

Can you explain the role of the res.render callback argument? When would it be necessary to use this callback argument, especially when there is already a template specified as the first argument? The following code snippet is taken from the official doc ...

In order to ensure proper alignment, adjust the width of the select element to match the width of the

Is there a way for the select element to adjust its width based on the length of the selected option? I want the default option value's width to be shorter, but once another option is selected, I'd like the select element to resize itself so that ...

Tips for navigating the HTML DOM without using window.scrollBy(x, y) (specifically for scrolling within an element)

Desiring to scroll down along with my selected document, I experimented with the following code. window.scrollTo(x, y); const body = document.getElementsByClassName("body")[0]; body.scrollTo(x, y); However, there are instances where it returns "undefined ...

Efficient Ways to Present and Personalize Indian Date and Time using JavaScript

Hey there, currently creating my website and need some assistance. I'm looking to display the date and time in different sections of the page. Having some trouble with getting Indian time to work properly using PHP. If you could help me out with Ja ...

Having difficulty with pagination within a callback function

I have been attempting to paginate in a call to a callback function, but I am encountering an error on the second call. Here is what my function does: let content = '' let size = 100 let from = 1 function result(size, from, callback) { ap ...

Oops! Property 'month' cannot be set on undefined value due to a TypeError

Despite not receiving any errors from Visual Studio Code, Iā€™m encountering an error in Chrome's console. Below is the code snippet from my interfaces.ts file: export interface Data1{ month: string; employeeName: string; date: string; employmentSta ...

Error encountered when attempting to retrieve token from firebase for messaging

I am currently working on implementing web push notifications using Firebase. Unfortunately, when attempting to access messaging.getToken(), I encounter an error stating "messaging is undefined." Below is the code snippet I am utilizing: private messaging ...

Encountered an error when attempting to use the 'removeChild' function on a node that is not a child of the specified node. This issue arose while interacting with an input box

I recently created a todo app with a delete functionality. However, after deleting an element successfully, I encountered an error when typing in the input box stating: Failed to execute 'removeChild' on 'Node': The node to be removed i ...

Creating a dropdown menu in Bootstrap 5 without using any of the Bootstrap

In my Angular application, I have a header with icons and pictures that I would like to use as dropdown menus. The code snippet for this functionality is shown below: <li class="nav-item dropdown"> <a class="nav-li ...

How can I show only the final four digits of an input field using Angular Material and AngularJS?

As a newcomer to Angular Material and Angular JS, I am striving to create an md-input field that displays only the last 4 digits in a masked format, such as "********1234". While my experience is currently limited to using md-input password fields where ...

What is the best way to detect a specific button press from an external component?

I need to integrate an external component written in Vue.js that contains multiple buttons. How can I specifically target and capture the click event of a particular button called firstButtonClick() within this external component? Here is how the External ...

What is the process for integrating ng-bootstrap into an Angular 5 project?

Has anyone encountered issues loading ng-bootstrap in their Angular project? I'm experiencing difficulties and would appreciate any insights. Thank you for your help! This is my app.module.ts file: import { BrowserModule } from '@angular/platf ...

Leveraging custom properties in HTML elements with JavaScript

I am in the process of creating a straightforward battleships game that utilizes a 10x10 table as the playing grid. My goal is to make it easy to adjust the boat length and number of boats, which is why I'm attempting to store data within the HTML obj ...

Is there a way to transfer the data from a chosen row into a different table?

My task involves using a table with two different conditions. In the first table, I display all incoming data. Then, in the second table (referred to as "select summary"), I want to show the row selected in the first table. To achieve this, I am utilizing ...

Real-time JQuery search with instant results

While utilizing a custom script to display search results on the page, I encountered an issue when typing long sentences. Each request goes to the server, resulting in delayed responses that stack up and cause the div to change quickly. This is not the des ...

Animating Divs with jQuery to Expand their Size

I am currently designing a services page for my portfolio website. The layout consists of three columns, with the central column containing a large box and the left and right columns each containing three smaller boxes. These smaller boxes function as clic ...

I'm encountering an issue where the data in my personalDeatail model's add value is not updating automatically. Can someone please help me

I've been struggling to automatically update the data in model personalDetail.add value when adding two column data. The added data appears correctly in the input box, but it's not updating in personalDetail.add. What am I missing here? Help need ...

Challenges arise when attempting to return an early resolution within promises in JavaScript

I have a function that determines further execution within itself and needs to use promises since it is asynchronous. An issue arises where the function continues execution even after resolving. Here's my code: function initializeApplication() { ...

By pressing enter, Combobox autocomplete feature automatically selects the first item in the suggestion list

I have successfully implemented a jQuery combobox autocomplete feature, similar to the one on the demo below. jQuery combobox autocomplete Is there a way to configure the jQuery combobox autocomplete to automatically select the top suggestion when the ...

Using formidable to parse form data in Node.js

Hello everyone, I'm a beginner with node.js and I'm currently working on setting up a file/image upload script. After successfully installing node on my VPS, I came across this helpful guide that assisted me in setting up the app with formidable ...