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
Majority Element II: Find Elements Appearing > n/3 TimesInput: nums = [3,2,3], n = 3, threshold = ⌊3/3⌋ = 1323index 0index 1index 2↓ Count Frequencies ↓3: count=22: count=1Filter: count > 1Output: [3]
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
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
78.9K Views
Medium Frequency
~25 min Avg. Time
2.2K 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