π Introduction
Given an array nums of size n, return the majority element β the element that appears more than βn / 2β times.
*Constraints typically include:
- It is guaranteed that the majority element always exists in the array.*
π‘ Approach & Key Insights
*The problem centers on identifying an element that occurs more than n/2 times. Three approaches are commonly used:
- Brute-force with nested loops.
- Better approach using hash map frequency counting.
- Optimal approach using Mooreβs Voting Algorithm for O(n) time and O(1) space.*
π οΈ Breakdown of Approaches
1οΈβ£ Brute Force / Naive Approach
- Explanation: For each element, count its frequency using a nested loop. If any element occurs more than βn/2β times, return it.
- Time Complexity:Β O(nΒ²) β due to nested iterations.
- Space Complexity:Β O(1)
- Example/Dry Run:
Input: [3, 2, 3]Step 1: Check 3 β appears 2 times β not > 1.5Step 2: Check 2 β appears 1 time β not > 1.5Return 3
2οΈβ£ Better Approach
- Explanation: Use a hash map to store frequencies of each number. As you update counts, if any value exceeds βn/2β, return it.
- Time Complexity:Β O(n) β single pass to count.
- Space Complexity:Β O(n) β for storing frequencies.
- Example/Dry Run:
Input: [2, 2, 1, 1, 1, 2, 2]Count Map:{2: 1}{2: 2}{2: 2, 1: 1}...{2: 4, 1: 3}Check: 4 > floor(7/2) = 3 β return 2
3οΈβ£ Optimal Approach
- Explanation: Use Mooreβs Voting Algorithm. Keep a count and a candidate. If count is zero, pick a new candidate. If current number equals candidate, increment count. Else decrement. At the end, the candidate is the majority element.
- Time Complexity:Β O(n) β single pass.
- Space Complexity:Β O(1) β constant space.
- Example/Dry Run:
Input: [2, 2, 1, 1, 1, 2, 2]Step-by-step:candidate = 2, count = 12 == 2 β count = 21 != 2 β count = 11 != 2 β count = 0 β candidate = 1, count = 11 == 1 β count = 22 != 1 β count = 12 != 1 β count = 0 β candidate = 2, count = 1Final candidate = 2 β return 2
π Complexity Analysis
Approach | Time Complexity | Space Complexity |
---|---|---|
Brute Force | O(nΒ²) | O(1) |
Hash Map Counting | O(n) | O(n) |
Mooreβs Voting Algo | O(n) | O(1) |
π Optimization Ideas
The Mooreβs Voting Algorithm is already optimal, with a single pass and constant space. If the array does not guarantee a majority element, a second pass is needed to verify the candidate.
π Example Walkthroughs & Dry Runs
Example: [3, 3, 4, 2, 4, 4, 2, 4, 4]Step-by-step:candidate = 3, count = 13 == 3 β count = 24 != 3 β count = 12 != 3 β count = 0 β candidate = 2...Final candidate = 4 β verify by count = 5n = 9 β β9/2β = 4 β 5 > 4 β return 4
π Additional Resources
Author: Neha Amin
Date: 19/07/2025