Majority Element II - Problem
Given an integer array nums of size n, find all elements that appear more than ⌊ n/3 ⌋ times.
The algorithm should run in linear time and use only constant extra space.
Note: There can be at most two elements that appear more than ⌊ n/3 ⌋ times in any array.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [3,2,3]
›
Output:
[3]
💡 Note:
Element 3 appears 2 times out of 3 total. Since 2 > ⌊3/3⌋ = 1, element 3 is a majority element.
Example 2 — No Majority
$
Input:
nums = [1]
›
Output:
[1]
💡 Note:
Element 1 appears 1 time out of 1 total. Since 1 > ⌊1/3⌋ = 0, element 1 is a majority element.
Example 3 — Two Majority Elements
$
Input:
nums = [1,2]
›
Output:
[1,2]
💡 Note:
Both elements appear 1 time out of 2 total. Since 1 > ⌊2/3⌋ = 0, both are majority elements.
Constraints
- 1 ≤ nums.length ≤ 5 × 104
- -109 ≤ nums[i] ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
Array with n=3, threshold = n/3 = 1
2
Count Elements
Find frequency of each unique element
3
Filter Result
Return elements with count > threshold
Key Takeaway
🎯 Key Insight: At most 2 elements can appear more than n/3 times, enabling Boyer-Moore optimization
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code