The brute-force solution uses a hash map to count frequencies, leading to:
The optimal solution uses Boyer-Moore Voting Algorithm, achieving O(n) time and O(1) space:
The “Majority Element” problem asks us to find the element in an array that appears more than ⌊n / 2⌋
times, where n
is the length of the array. It is guaranteed that such an element always exists.
For example:
Input: [3, 2, 3]
→ Output: 3
Input: [2, 2, 1, 1, 1, 2, 2]
→ Output: 2
This problem highlights techniques in frequency counting and vote-based tracking. It’s a stepping stone to more advanced voting or consensus algorithms and teaches you how to efficiently identify dominant elements in linear time and constant space.
A straightforward way to solve the problem is by using a hash map (or dictionary) to count the frequency of each number in the array.
n / 2
, return it as the majority element.This approach runs in linear time but requires O(n) space in the worst case, which is not optimal given the constraints.
A more elegant and space-efficient method is the Boyer-Moore Voting Algorithm. This algorithm is based on the fact that the majority element appears more than all other elements combined, so it can “cancel out” minority votes.
candidate = null
and count = 0
.count == 0
, set candidate = current number
.current number == candidate
, increment count
.count
.candidate
. Since a majority element is guaranteed to exist, no second verification is needed.
Input: [2, 2, 1, 1, 1, 2, 2]
Tracking steps:
Final candidate is 2
, which is the majority element.
Time Complexity: O(n), where n is the number of elements in the array.
Space Complexity: O(1), since the Boyer-Moore algorithm only uses two variables.
The “Majority Element” problem is a powerful lesson in identifying dominant patterns with minimal memory. The Boyer-Moore Voting Algorithm transforms what seems like a counting problem into a clever linear scan using a vote-counter technique. It's one of the most elegant examples of reducing space complexity without sacrificing performance.