sagelearnai

Majority Element

Difficulty: Easy · Pattern: Hashing · LeetCode #169

Return the element that appears more than ⌊n/2⌋ times in nums (it always exists). Follow-up: O(1) extra space.

Examples

text
[3, 2, 3]              →  3
[2, 2, 1, 1, 1, 2, 2]  →  2

Hints

  1. A hash-map count works in O(n) space.
  2. Pair off different elements: the majority survives the cancellation.

Approach

Boyer–Moore voting: keep a candidate and a count. For each x: if count is 0, set candidate = x; then count += 1 if x == candidate, else count −= 1. Each non-majority element can cancel at most one majority element, and the majority has more than half, so it ends as the candidate. O(n) time, O(1) space.

Complexity

Time: O(n). Space: O(1).

Python solution
def majorityElement(nums):
    cand, count = None, 0
    for x in nums:
        if count == 0:
            cand = x
        count += 1 if x == cand else -1
    return cand
JavaScript solution
function majorityElement(nums) {
  let cand = null, count = 0;
  for (const x of nums) { if (count === 0) cand = x; count += x === cand ? 1 : -1; }
  return cand;
}