Boyer-Moore Majority Vote for $\lfloor n/3 \rfloor$: $O(n)$ Time and $O(1)$ Space
The Boyer-Moore Majority Vote algorithm can be extended from the standard $> \lfloor n/2 \rfloor$ problem to identify elements appearing strictly more than $\lfloor n/k \rfloor$ times. For $k = 3$, an array of length $n$ can contain at most two such elements:
$$\text{If three distinct elements each appeared } > \frac{n}{3} \text{ times, total elements } > 3 \times \frac{n}{3} = n \quad (\text{a contradiction})$$
By maintaining two candidate slots and two independent counters, we can filter the entire array down to at most two potential winners in a single pass, followed by a second verification pass to guarantee mathematical validity.
The Mathematical Intuition: Triplet Cancellation
- In the standard algorithm ($> n/2$), we cancel out pairs of distinct numbers (
1 candidate + 1 opponent). - In the generalized algorithm ($> n/3$), we cancel out triplets of distinct numbers (
2 candidates + 1 opponent).
Whenever we encounter three mutually distinct numbers, we discard one copy of each. Because each cancellation consumes three distinct values, any element appearing strictly more than $n/3$ times cannot be completely eliminated.
Algorithmic Execution (Two Passes)
Pass 1: Candidate Election ($O(n)$)
Maintain two candidates (cand1, cand2) and two counters (count1 = 0, count2 = 0):
- Match Candidate 1: If
num == cand1, incrementcount1. - Match Candidate 2: Else if
num == cand2, incrementcount2. - Fill Slot 1: Else if
count1 == 0, assigncand1 = numand setcount1 = 1. - Fill Slot 2: Else if
count2 == 0, assigncand2 = numand setcount2 = 1. - Triplet Discard: Else, decrement both
count1andcount2simultaneously (canceling three distinct values).
Critical Ordering: The checks for matching an existing candidate must come before checking if a count is zero. Otherwise, duplicate keys can overwrite both candidate slots simultaneously.
Pass 2: Verification Pass ($O(n)$)
Unlike the $> n/2$ variant where a majority element might be guaranteed to exist, an array is not guaranteed to have any element appearing $> \lfloor n/3 \rfloor$ times (e.g., [1, 2, 3, 4, 5]). We must iterate through the array once more to count the exact frequencies of cand1 and cand2, adding them to the final result only if their count exceeds $\lfloor n/3 \rfloor$.
Implementation (C++ & Python)
C++ Implementation
#include <vector>
std::vector<int> majorityElement(const std::vector<int>& nums) {
int cand1 = 0, cand2 = 0;
int count1 = 0, count2 = 0;
// Pass 1: Determine the top two surviving candidates
for (int num : nums) {
if (num == cand1) {
count1++;
} else if (num == cand2) {
count2++;
} else if (count1 == 0) {
cand1 = num;
count1 = 1;
} else if (count2 == 0) {
cand2 = num;
count2 = 1;
} else {
// Found a 3rd distinct element: cancel out one instance of all three
count1--;
count2--;
}
}
// Pass 2: Verify candidate frequencies
count1 = 0;
count2 = 0;
for (int num : nums) {
if (num == cand1) count1++;
else if (num == cand2) count2++;
}
std::vector<int> result;
int threshold = nums.size() / 3;
if (count1 > threshold) result.push_back(cand1);
if (count2 > threshold) result.push_back(cand2);
return result;
}
Python Implementation
def majority_element(nums: list[int]) -> list[int]:
cand1, cand2 = None, None
count1, count2 = 0, 0
# Pass 1: Candidate identification via triplet cancellation
for num in nums:
if num == cand1:
count1 += 1
elif num == cand2:
count2 += 1
elif count1 == 0:
cand1, count1 = num, 1
elif count2 == 0:
cand2, count2 = num, 1
else:
count1 -= 1
count2 -= 1
# Pass 2: Exact count validation
threshold = len(nums) // 3
result = []
for cand in (cand1, cand2):
if cand is not None and nums.count(cand) > threshold:
result.append(cand)
return result
Complexity Analysis
| Metric | Complexity | Explanation |
|---|---|---|
| Time Complexity | $O(n)$ | Pass 1 processes $n$ elements in $O(n)$ time. Pass 2 iterates $n$ elements to verify up to two candidates. Total time is $O(n) + O(n) = O(n)$. |
| Auxiliary Space | $O(1)$ | Memory usage is strictly constant. Only four scalar variables (cand1, cand2, count1, count2) are used regardless of the input size $n$. |
Summary of Edge Cases Handled
- No Majority Element: Inputs like
[1, 2, 3, 4]produce candidates during Pass 1, but Pass 2 cleanly filters them out, returning an empty list[]. - Single Dominant Element: Inputs like
[3, 3, 3, 2, 1]safely assign one slot to3and leave or overwrite the second slot; Pass 2 validates only[3]. - Identical Elements: Inputs like
[2, 2, 2, 2]incrementcount1consistently without improperly splitting the count across both candidate slots.
