DEV Community

Cover image for find the majority element
chandra penugonda
chandra penugonda

Posted on • Updated on

find the majority element

Good morning! Here's your coding interview problem for today.

Given an array of size n, find the majority element. The majority element is the element that appears more than [n/2] times.

You may assume that the array is non-empty and the majority element always exist in the array.

Example

const majorityElement = nums => {

};

console.log(majorityElement([2,2,1,1,1,2,2]))  // 2
Enter fullscreen mode Exit fullscreen mode

Solution

function majorityElement(nums) {
  const obj = {};
  for (const num of nums) {
    obj[num] = (obj[num] || 0) + 1;
    if (obj[num] > nums.length / 2) return num;
  }
}
Enter fullscreen mode Exit fullscreen mode

Explanation

  • Iterate through the array and count the frequency of each number in a hash map.
  • If any number's frequency is greater than n/2, return that number immediately.
  • Otherwise, return the majority number after full iteration.

Top comments (0)