## DEV Community is a community of 601,436 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

# 169. Majority Element (javscript solution)

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;
}
};
``````