DEV Community

codingpineapple
codingpineapple

Posted on

3 2

169. Majority Element (javscript solution)

Description:

Given an array nums of size n, return the majority element.

The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.

Solution:

Time Complexity : O(n)
Space Complexity: O(n)

// Use a hashmap to save the count of each element
// Return the first number whose count is equal to the majority
var majorityElement = function(nums) {
    // Define the majority number to reach
    const majority = Math.round(nums.length / 2)
    const map = {}
    for(let i = 0; i<nums.length; i++){
        const cur = nums[i]
        // Increment the count of each number in the hashmap
        map[cur] = (map[cur] || 0) + 1
        // Return the first number whose count is equal to the majority
        if(map[cur]===majority) return cur;
    }
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay