SDE & MLE Prep

229. Majority Element II

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]