Find the most frequent element in an array

Learn how to find the most frequent element in an array.

Given an array of elements we have to find the element with most frequency or count. If there are two elements with most occurrence then return the first.

Example

Input:
[1, 1, 1, 2, 2, 2, 3, 3, 4]
[2, 2, 2, 3, 3, 3, 4, 4, 4, 2, 5, 5, 5, 6, 6]

Output:
1
2

In the first example, there are three elements with same count 1, 2 & 3, but has 1 has occurred first so we have returned it.

In the second example, 2 is with most count of 4.

Program to find the most frequent element in an array.

One way to solve this problem is to use two nested loops to count the frequency of elements. But it will work in O(n^2).

The other method is very efficient. We first iterate the array and store the count in hashmap and then find the element with most count from the hashamp. As we are using two loops one after another it will result in O(n + n) = O(n).

Implementation

  • Count the frequency of elements and store them in an object as key value pair, because objects can be used as a dictionary in javascript.
  • Iterate this object and return the element with most occurrence.
     const leastFrequent = arr => {
        //Store the number counts in object
        const count = arr.reduce((a, b) => {
          if (!a[b]) {
            a[b] = 1;
          } else {
            a[b]++;
          }

          return a;
        }, {});

        let maxCount = Number.MIN_SAFE_INTEGER;
        let numberWithLeastCount = 0;

        //Find the number with most count
        for (const [key, value] of Object.entries(count)) {
          if (value > maxCount) {
            maxCount = value;
            numberWithLeastCount = key;
          }
        }

        return numberWithLeastCount;
      };

We have used array reduce to accumulate the count of the elements and then iterate the object by pulling all the entries with Object.entries() and return the key with max value.

Input:
console.log(leastFrequent([1, 1, 1, 2, 2, 2, 3, 3, 4]));
console.log(leastFrequent([2, 2, 2, 3, 3, 3, 4, 4, 4, 2, 5, 5, 5, 6, 6]));

Output:
1
2

Time complexity: O(n).
Space complexity: O(n).