Coder's Cat

LeetCode: Majority Element

2020-02-07

Challenge Description

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 1:

Input: [3,2,3]
Output: 3

Example 2:

Input: [2,2,1,1,1,2,2] 
Output: 2

Naive Solution

Iterate over all the elements in array, use a unordered_map to store the counts of current element, when one element’s count > size/2, it’s OK to break the loop and return the element.

Time complexity: $O(N)$.

class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int, int> counts;
unordered_map<int, int>::iterator it;
for(int i=0; i < nums.size(); i++) {
int t = nums[i];
it = counts.find(t);
if(it == counts.end())
counts[t] = 1;
else
counts[t] += 1;
if(counts[t] > nums.size() / 2)
return t;
}
return 0;
}
};

Approach with sorting

If we sort the array, the element at index size/2 will be the answer.

Time complexity: $O(NlogN)$.

class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(), nums.end());
return nums[nums.size()/2];
}
};

Preparing for an interview? Checkout this!