DEV Community

loading...

169. Majority Element (javscript solution)

cod3pineapple profile image codingpineapple ・1 min read

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

Discussion (0)

pic
Editor guide