229. Majority Element II
Asked at 11Amazon43Bloomberg42Google40Microsoft40Meta35Zenefits100Intel66Waymo58Accenture44Infosys30tcs27
Problem
Return every value that appears more than ⌊n / 3⌋ times in nums (there can be at most two), in any order.
Example: [3,2,3] → [3]; [1,2] → [1,2]
Constraints: follow-up: O(n) time and O(1) space.
At most two values can appear more than n/3 times. Extended Boyer–Moore voting keeps two candidates with counters: a match increments its counter, an empty slot adopts the value, otherwise both counters drop (cancelling a triple of distinct values). A second pass verifies the candidates' real counts.
Complexity: O(n) time, O(1) space.
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
c1, c2, n1, n2 = None, None, 0, 0
for x in nums:
if x == c1:
n1 += 1
elif x == c2:
n2 += 1
elif n1 == 0:
c1, n1 = x, 1
elif n2 == 0:
c2, n2 = x, 1
else:
n1, n2 = n1 - 1, n2 - 1
return [c for c in (c1, c2) if c is not None and nums.count(c) > len(nums) // 3]
assert Solution().majorityElement([3, 2, 3]) == [3]
assert Solution().majorityElement([1]) == [1]
assert sorted(Solution().majorityElement([1, 2])) == [1, 2]
assert sorted(Solution().majorityElement([2, 2, 1, 1, 1, 2, 2])) == [1, 2]
assert Solution().majorityElement([1, 2, 3, 4]) == []
class Solution {
public List<Integer> majorityElement(int[] nums) {
int c1 = 0, c2 = 1, n1 = 0, n2 = 0; // distinct placeholders; verified below
for (int x : nums) {
if (x == c1) n1++;
else if (x == c2) n2++;
else if (n1 == 0) { c1 = x; n1 = 1; }
else if (n2 == 0) { c2 = x; n2 = 1; }
else { n1--; n2--; }
}
List<Integer> res = new ArrayList<>();
for (int c : new int[]{c1, c2}) {
int cnt = 0;
for (int x : nums) if (x == c) cnt++;
if (cnt > nums.length / 3) res.add(c);
}
return res;
}
}
func majorityElement(nums []int) []int {
c1, c2, n1, n2 := 0, 1, 0, 0 // two candidates (distinct initial values)
for _, x := range nums {
switch {
case x == c1:
n1++
case x == c2:
n2++
case n1 == 0:
c1, n1 = x, 1
case n2 == 0:
c2, n2 = x, 1
default:
n1, n2 = n1-1, n2-1
}
}
res := []int{}
for _, c := range []int{c1, c2} {
cnt := 0
for _, x := range nums {
if x == c {
cnt++
}
}
if cnt > len(nums)/3 {
res = append(res, c)
}
}
return res
}