2

I am currently being faced with this problem where I am trying to find the most occurring or frequent element in an array.

For example:

const arr = [1,2,1,1,1,2,2,2,1] (Most occuring is: 1)

Follow up: What if I want to get the second-most occurring element?

Here's my solution:

function returnMostOccurring(arr) {
   const obj = {};
   arr.forEach(item => {
      if(!obj[item]) obj[item] = 1;
      else obj[item]++;
   })

   const res =  Object.entries(obj).sort((a,b) => b[1]-a[1]);
   return res.shift();
}

I figured this is not the most optimal way to solve this problem (O(nLogN) time complexity)

What is the best way to handle this kind of use case?

TechnoCorner
  • 4,879
  • 10
  • 43
  • 81

1 Answers1

4

You could take a single loop with a variable for the element with the actual max count and an object for keeping the counts of the elements.

function mostOccurringElement(array) {
    var max = array[0],
        counter = {},
        i = array.length,
        element;
    
    while (i--) {
        element = array[i];
        if (!counter[element]) counter[element] = 0;
        counter[element]++;
        if (counter[max] < counter[element]) max = element;
    }
    return max;
}

const array = [1, 2, 1, 1, 1, 2, 2, 2, 1];

console.log(mostOccurringElement(array));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392