Majority Element II - Problem

You're given an integer array of size n, and your mission is to find all the truly dominant elements - those that appear more than ⌊n/3⌋ times.

This is a step up from the classic "Majority Element" problem where we looked for elements appearing more than ⌊n/2⌋ times. Here, we're looking for elements that appear in more than one-third of the array positions.

Key insight: There can be at most 2 elements that satisfy this condition in any array. Why? If three elements each appeared more than n/3 times, their total count would exceed n, which is impossible!

Example: In array [3,2,3] with n=3, we need elements appearing more than ⌊3/3⌋ = 1 time. Element 3 appears 2 times, so it's a majority element.

Input & Output

example_1.py — Basic Case
$ Input: [3,2,3]
Output: [3]
💡 Note: Array length n=3, so threshold = ⌊3/3⌋ = 1. Element 3 appears 2 times > 1, element 2 appears 1 time ≤ 1. Only 3 qualifies.
example_2.py — Multiple Majority
$ Input: [1,1,1,3,3,2,2,2]
Output: [1,2]
💡 Note: Array length n=8, so threshold = ⌊8/3⌋ = 2. Element 1 appears 3 times > 2, element 2 appears 3 times > 2, element 3 appears 2 times ≤ 2. Elements 1 and 2 qualify.
example_3.py — No Majority
$ Input: [1,2,3,4,5,6]
Output: []
💡 Note: Array length n=6, so threshold = ⌊6/3⌋ = 2. Each element appears only once, which is ≤ 2. No elements qualify as majority.

Constraints

  • 1 ≤ nums.length ≤ 5 × 104
  • -109 ≤ nums[i] ≤ 109
  • Follow-up: Could you solve the problem in linear time and in O(1) space?

Visualization

Tap to expand
Election Analogy: Finding Popular CandidatesVoters:ABAALeading Candidates:Candidate AVotes: 3Candidate BVotes: 1Victory Threshold:Need more than n/3 = 4/3 = 1.33 votesCandidate A: 3 votes > 1.33 ✓ WINNERCandidate B: 1 vote < 1.33 ✗🏆 WINNERCandidate A
Understanding the Visualization
1
Campaign Phase
Two candidates compete for support, gaining and losing votes
2
Vote Counting
When conflicts arise, both candidates lose support (like negative campaigning)
3
Final Tally
After campaigning, we verify which candidates actually have >n/3 votes
4
Winners Declared
Only verified candidates with sufficient support are declared winners
Key Takeaway
🎯 Key Insight: Just like in elections, at most 2 candidates can win when each needs >1/3 support, since 3 winners would need >100% total votes!
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28 Apple 22
52.4K Views
High Frequency
~18 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen