Hiprup

How do you find the most frequent element in an array?

Count occurrences, then pick the highest.

  1. Build a frequency map: loop the array and tally each value.

  2. Track the item with the highest count as you go, or scan the map afterward.

  3. Return that item.

Efficient: a Map or plain object as the counter gives an O(n) solution.

// Method 1: Object as frequency map
function mostFrequent(arr) {
  const freq = {};
  let maxCount = 0;
  let maxElement = null;

  for (const item of arr) {
    freq[item] = (freq[item] || 0) + 1;
    if (freq[item] > maxCount) {
      maxCount = freq[item];
      maxElement = item;
    }
  }

  return { element: maxElement, count: maxCount };
}

console.log(mostFrequent([1, 3, 2, 1, 4, 1, 3, 3, 3]));
// { element: 3, count: 4 }

// Method 2: Using reduce
function mostFrequentReduce(arr) {
  const freq = arr.reduce((acc, item) => {
    acc[item] = (acc[item] || 0) + 1;
    return acc;
  }, {});

  return Object.entries(freq).reduce((max, [key, count]) =>
    count > max[1] ? [key, count] : max
  , ['', 0]);
}

// Method 3: Using Map (handles any type)
function mostFrequentMap(arr) {
  const map = new Map();
  for (const item of arr) {
    map.set(item, (map.get(item) || 0) + 1);
  }
  return [...map.entries()].sort((a, b) => b[1] - a[1])[0];
}

Method 1 builds a frequency object in one pass (O(n)), tracking the max as it goes. Method 2 uses reduce for the frequency map, then Object.entries + reduce to find the max.

Method 3 uses Map (handles non-string keys like objects). All are O(n) time, O(n) space.

The single-pass approach (tracking max while building frequency map) is optimal. O(n) time, O(n) space. The reduce version is more concise.

Use Map instead of Object when keys might not be strings. Show both approaches for completeness.

How do you find the most frequent element in an array? | Hiprup