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 - Boyer-Moore Voting INPUT Array nums (n=3) 3 idx 0 2 idx 1 3 idx 2 Threshold: n/3 = 3/3 = 1 Need count > 1 (at least 2) Element Counts: 3 appears: 2 times 2 appears: 1 time At most 2 elements can appear > n/3 times ALGORITHM STEPS 1 Initialize Candidates cand1=null, cnt1=0 cand2=null, cnt2=0 2 First Pass - Vote For each num in array: - Match cand? Increment - Empty slot? Assign - Else decrement both Voting Trace: num=3: c1=3,cnt1=1 num=2: c2=2,cnt2=1 num=3: c1=3,cnt1=2 Final: c1=3, c2=2 3 Second Pass - Verify Count actual occurrences 3-->2, 2-->1 4 Filter Results Keep if count > n/3 FINAL RESULT Majority Elements Found: [3] Verification: Element 3: count=2 > 1 [OK] Element 2: count=1 <= 1 [NO] Output Array: [3] Key Insight: Boyer-Moore Voting uses the fact that at most 2 elements can appear more than n/3 times. We track 2 candidates with counters. When we see a different element, we decrement both counters. This ensures true majority elements survive. Time: O(n), Space: O(1) - optimal solution! TutorialsPoint - Majority Element II | Boyer-Moore Majority Vote - Optimal
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