SDE & MLE Prep

169. Majority Element

Problem

Return the majority element of nums, the value that appears more than ⌊n / 2⌋ times. It is guaranteed to exist.

Example: [2,2,1,1,1,2,2] → 2

Constraints: n ≤ 5·10⁴. Follow-up: O(n) time and O(1) space.

Boyer–Moore voting: keep a candidate and a counter. Same value → +1, different → −1; at 0 adopt the current value. The majority (> n/2) can't be cancelled out.

Complexity: O(n) time, O(1) space.

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        cand, cnt = None, 0
        for x in nums:
            if cnt == 0:
                cand = x
            cnt += 1 if x == cand else -1
        return cand