BudiBadu Logo

Majority Element

Hash Table Easy 1 views
Like0

Ever been in a situation where one voice clearly drowns out the rest? That’s exactly what the Majority Element is! You’re given an array of numbers, and your mission is to find the one that appears more than half the time (more than n/2). You can always assume that such a "leader" exists in the crowd.

The "secret sauce" here is a Frequency Map. While there are exotic ways to solve this (like Boyer-Moore Voting), the most intuitive way is to keep a tally of each number as you scan. Think of it like an election: every time you see a number, you give it a vote in your Map. As soon as a number’s vote count crosses the "more than half" threshold, you declare it the winner! This approach gives you a linear O(n) efficiency, making it perfect for large datasets. It’s a fundamental pattern for identifying dominance in any collection of data before moving to more complex stats!

Examples

Example 1
Input
nums = [3,2,3]
Output
3
Explanation

3 appears 2 times, more than n/2.

Example 2
Input
nums = [2,2,1,1,1,2,2]
Output
2
Explanation

2 appears 4 times out of 7.

Example 3
Input
nums = [1]
Output
1
Explanation

Only element is majority.

Algorithm Flow

Recommendation Algorithm Flow for Majority Element - Budibadu
Recommendation Algorithm Flow for Majority Element - Budibadu

Best Answers

java
import java.util.*;
class Solution {
    public int majority_element(int[] nums) {
        Map<Integer, Integer> freq = new HashMap<>();
        int limit = nums.length / 2;
        for (int x : nums) {
            freq.put(x, freq.getOrDefault(x, 0) + 1);
            if (freq.get(x) > limit) return x;
        }
        return nums.length > 0 ? nums[0] : 0;
    }
}