AlgoMaster Logo

Majority Element

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

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