AlgoMaster Logo

Majority Element

Last Updated: February 6, 2026

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Understanding the Problem

Before diving into solutions, let us make sure we understand what a "majority element" really means.

An element is the majority if it appears more than n/2 times. This is a strict inequality. For an array of size 5, a majority element must appear at least 3 times. For an array of size 6, it must appear at least 4 times.

This definition has a powerful implication: there can be at most one majority element. Think about it. If one element appears more than half the time, there simply are not enough positions left in the array for any other element to also appear more than half the time.

The problem guarantees that a majority element always exists. In a real interview, you might want to clarify this assumption. Without it, you would need to verify that your candidate actually appears more than n/2 times before returning it.

Another key observation: since the majority element appears more than half the time, if you pair up each occurrence of the majority element with a non-majority element, you would still have majority elements left over. This insight becomes crucial when we discuss the Boyer-Moore algorithm.

Approaches

1. Brute Force

Intuition:

The brute-force method checks each element in the array and counts how many times it appears. If any element occurs more than n/2 times (where n is the length of the array), that element is the majority element.

This approach is simple to understand but inefficient because it performs a full scan for every element.

Code:

2. HashMap

Intuition:

We can optimize the brute force approach by using a HashMap to store the frequency of each element.

Traverse the array, and increment the counter for each element encountered. The element with a frequency greater than n/2 will be the majority element.

Code:

3. Sorting

Intuition:

If we sort the array, all identical elements naturally group together. Since the majority element appears more than n/2 times, it must occupy the entire middle region of the sorted array.

That means the element at index n/2 will always be the majority element.

Code:

Example Walkthrough:

Input:

0
2
1
2
2
1
3
1
4
1
5
2
6
2

After sorting:

0
1
1
1
2
1
3
2
middle
4
2
5
2
6
2

4. Boyer-Moore Voting Algorithm

Intuition:

The Boyer-Moore Voting Algorithm efficiently finds the majority element in linear time.

It maintains:

  • candidate: current guess for the majority
  • count: confidence in the candidate

As you scan:

  • If count == 0, adopt the current number as the new candidate.
  • If the current number equals candidate, increment count; otherwise, decrement it.

If a true majority exists, this process guarantees the final candidate is that majority.

Code:

Example Walkthrough:

0
2
1
2
2
1
3
1
4
1
5
2
6
2
candidate = 2, count = 0
Step 1 / 8