Majority Element II Problem
Description
LeetCode Problem 229.
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.
Example 1:
Input: nums = [3,2,3]
Output: [3]
Example 2:
Input: nums = [1]
Output: [1]
Example 3:
Input: nums = [1,2]
Output: [1,2]
Constraints:
- 1 <= nums.length <= 5 * 10^4
- -10^9 <= nums[i] <= 10^9
Solution
Approach: Boyer-Moore Voting with Two Candidates
Counting with a hash map works in O(n) time but needs O(n) space. Voting finds the answer with O(1) space.
At most two values can appear more than ⌊n/3⌋ times, since three such values would need more than n elements. So we track two candidates, each with a count:
- If
xequals a candidate, increase that candidate's count. - Otherwise, if a count is
0, makexthat candidate with count1. - Otherwise, decrease both counts. This removes three different values at once:
xand one copy of each candidate.
Each cancellation removes three different values, so it removes at most one copy of any value. There are at most n/3 cancellations, fewer than the copies of a value that appears more than n/3 times, so that value is never cancelled out completely and is still a candidate at the end.
The opposite is not true: a candidate may appear only a few times. So the second pass counts each candidate and keeps those with a count greater than ⌊n/3⌋. Skip the second candidate if it equals the first. Both start with the same placeholder value, so without this check a value could be added twice (for example [0, 0]).
Check x == candidate1 and x == candidate2 before the zero-count cases, so the same value never fills both slots.
Complexity: O(n) time, where n is the length of nums, and O(1) extra space.
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
# At most two values can appear more than n/3 times. Find two candidates by
# cancelling out groups of three different values (Boyer-Moore voting).
candidate1, count1 = 0, 0
candidate2, count2 = 0, 0
for x in nums:
if x == candidate1:
count1 += 1
elif x == candidate2:
count2 += 1
elif count1 == 0:
candidate1, count1 = x, 1
elif count2 == 0:
candidate2, count2 = x, 1
else:
# x and one copy of each candidate cancel out.
count1 -= 1
count2 -= 1
# The candidates are only possible answers: count them to check.
result = []
if nums.count(candidate1) > len(nums) // 3:
result.append(candidate1)
if candidate2 != candidate1 and nums.count(candidate2) > len(nums) // 3:
result.append(candidate2)
return result
Now write it from memory
Close the write-up and solve it yourself against the tests.