Is there a quicker alternative for handling lengthy inputs?

Imagine I come across this particular challenge:

And here's how I tackle it:

function bcc(arr) {
    let res = 0;
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] == Math.max(...arr)) {
            res++;
        }
    }
    return res;
}

console.log(bcc([4, 4, 3, 1]));

Initially, my solution works well for an array like [4, 4, 3, 1]. However, when HackerRank presents me with a massive array containing 100,000 elements and expecting an output of 7147, my code fails due to timeout issues. This resulted in me getting only 5 out of 9 problems correct.

Could you offer me a more efficient solution that not only solves this problem quicker but can also be applied to other challenges as well?

Answer №1

Determine the highest value within the array in advance, rather than with each iteration, and utilize reduce for conciseness:

function findMaxOccurrence(arr) {
  const max = Math.max(...arr);
  return arr.reduce((a, b) => a + (b === max), 0);
}

This decreases the overall computational complexity from O(n ^ 2) to O(n).

Alternatively, you can follow a similar approach as your initial code:

function findMaxOccurrence(array) {
  const max = Math.max(...array);
  let result = 0;
  for (let i = 0; i < array.length; i++) {
    if (array[i] == max) {
      result++;
    }
  }
  return result;
}

Answer №2

The flaw in the solution provided is that it has a time complexity of O(n^2), as pointed out by another answer. This inefficiency arises because the maximum value is recalculated during each iteration of the loop instead of being calculated just once. The reason for this is that Math.max needs to traverse the entire array to determine the maximum value, leading to redundant calls within the loop.

While computing the max value at the start is functional, it is not optimal. A more efficient approach would be to calculate it in real-time as the loop progresses. By doing so, the time complexity is reduced from O(2n) to O(n), resulting in improved performance.

function birthdayCakeCandles(ar) {
    var max = 0;
    var candleCount = 0;
    for(var i = 0; i < ar.length; i++) {
        if(ar[i] > max) {
            max = ar[i];
            candleCount = 1;
        } else if (ar[i] === max) {
            candleCount++;
        }
    }
    return candleCount;
}

This revised solution iterates through the array only once, resetting the candle count when encountering a new maximum value and resuming counting thereafter.

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

Lock it up or leave it open - that is the question

My JavaScript/jQuery web application features an object that is accessed for reading and writing by users through DOM events, as well as by the server via web sockets or xhr requests. Although I am aware that JavaScript is single-threaded, I have concerns ...

Using jQuery to gradually fade out my sidebar (div)

I have written the following code to hide my sidebar when the screen width is less than 1024 pixels, but it doesn't seem to be working. It worked fine on a previous website, so I'm not sure what the issue is here. Any help would be greatly apprec ...

Navigating through various versions of admin-on-rest can be perplexing

This question is likely directed towards maintainers. Currently, I am using the stable version of admin-on-rest (https://www.npmjs.com/package/admin-on-rest) which is at 1.3.4. It seems that the main project repository is only receiving bug fixes, while ...

Clicking the Javascript styling toggle does not function properly on the initial click

I'm currently developing an HTML application with a sidebar menu that toggles on click. However, I've encountered an issue where the menu doesn't appear until the second click. The first click seems to have no effect. Here's the CSS co ...

Tips on creating a dropdown list in HTML with the previous year's worth of data

Currently, I am facing an issue with a dropdown list on my web application. The requirement is to display the last 12 months in proper order within the dropdown list. To clarify, let's say it is February 2016, the dropdown list should start from March ...

Using browserify with html2canvas is causing compatibility issues

When I initially tested html2canvas as a standalone script, it worked perfectly. However, when attempting to use the npm package version, it is proving to be quite uncooperative. Essentially, it does not execute any actions or trigger the then function. T ...

The toggle function for the classList ('open') is functioning correctly and can be seen in the inspect element tool, however, the website is not displaying the associated style

How can I make the .nav show styles in .open after clicking #menu-icon? Note: I used Bootstrap to create the nav HTML <!-- logo --> <div class="logo"> <img src="assets/logo.png" alt="logo g's shop& ...

How to automatically select the first item in a populated dropdown list using Vue JS

My HTML select element is populated with options from a server, but when using v-model, it initially selects an empty option instead of the first one. I came across a solution on a post which suggests selecting the first option manually, but since the dat ...

Issue with jQuery animation: Background color does not change upon scrolling

Here is my fiddle link: https://jsfiddle.net/jzhang172/owkqmtcc/5/ I am attempting to change the background color of the "content" div when scrolling anywhere within it. The goal is for the background color to change when scrolling and revert back to its ...

Limit the usage of map() to solely operate on a collection of headers stored within an array generated from a specified range

I need to limit the map functionality to only include columns within the specified range that are also present in the headers list, which is a subset of the values in v[0]. This ensures that only values from columns listed in the headers array will be mo ...

`In AngularJS, the default selection option is not functioning as expected`

I'm struggling with a particular issue in my code. <select ng-model="selected_student" class="form-control"> <option ng-repeat="obj in students" value="{{obj.id}}">{{obj.name}}</option> </select> When I try to set the sel ...

What could be causing the jQuery slidedown to malfunction within my table?

My slider is not working when I include a table on my website. The slider works fine without a table, but I need to display members in a table format. Can anyone help me identify the issue with my code? The information needs to be displayed below the nam ...

Creating an Array using MySQL Database

Having a database connection, I attempted to create an array but encountered what seems like a problem. Below is the code of my array: $var = "SELECT SUBSTRING(KayitTarihi,1,4) AS year,SUBSTRING(KayitTarihi,6,2) AS month,SUBSTRING(KayitTarihi,9,2) AS day, ...

Decide whether Variable Name is equal to the String

I am currently facing an issue. var myArrayVariable1 = new Array(); var myStringVariable1 = 'myArrayVariable1'; var myStringVariable2 = 'myArrayVariable2'; Is there a way to determine if one of the strings matches the variable name? F ...

Looking to utilize vue.js to alter the color of the <li> element when a select option is chosen

I'm a beginner in vue.js and I'm attempting to change the background color by using the select option. Despite trying the cueCardsColor method, nothing seems to be happening. <ul> <li :class="+ cueCardColor"> <sele ...

Discovering a method to detect clicks outside of a React functional component

Looking to identify when a click occurs outside of a React functional component. After stumbling upon an article, I followed the provided code but unfortunately, it didn't work as expected. Despite identifying the issue, I am still searching for a so ...

One-stop hub for JavaScript API URLs

We are currently developing a web application using .NET Core and React, which involves integrating with various APIs. Throughout the project, we are making AJAX calls to fetch data from these APIs. Our continuous integration and continuous deployment (C ...

Error: Angular does not recognize x2js XML format

I'm attempting to adapt this particular example to utilize xml as json data. However, I am encountering some issues with the code. courses = x2js.xml_str2json(data); console.log(courses.books.course); $scope.todos = courses.books.course; In the XML ...

How to Use an Object Created from a Different Class in TypeScript

Scenario In the development process, I am using an auth.service.ts. This service is responsible for fetching user information from the database upon login. The retrieved data is then used to create a new user object. Here is a snippet of the code: user: ...

Can you please point out the location of the error in the Java Script code

Our application is developed using Yii2 framework and incorporates Kartik's star-rating widget. However, there seems to be an error in the JavaScript code: Error message from console: Check out the problematic code snippet: <?php $js = ...