Majority Element

Easy

Topics
ArrayHash Table

Given an array nums of size n, return the majority element (the one appearing more than n/2 times). It always exists.

Example 1

302132
the majority value
The majority element occupies more than half the cells, so pairing it off against every other value still leaves it standing.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [3,2,3]
Output: 3

Example 2

20211213142526
the majority value
Input:  nums = [2,2,1,1,1,2,2]
Output: 2

Constraints

  • n == nums.length
  • 1 <= n <= 5*10^4
  • The majority element always exists.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Because the majority element occurs more than n/2 times, if we cancel out pairs of different elements, the majority can never be fully cancelled — it will always survive.

Boyer–Moore voting implements this: hold one candidate and a counter; matching votes add, differing votes subtract.

Approach

  1. Keep candidate and count = 0.
  2. When count hits 0, adopt the current element as the candidate.
  3. If the element equals the candidate, increment count; otherwise decrement.
  4. The final candidate is the majority (guaranteed to exist).

Walkthrough

nums = [2, 2, 1, 1, 1, 2, 2]
2: cand=2 cnt=1
2: cnt=2
1: cnt=1
1: cnt=0
1: cand=1 cnt=1
2: cnt=0
2: cand=2 cnt=1  -> answer 2

Complexity

  • Time — O(n): one pass.
  • Space — O(1): two variables, versus O(n) for a frequency map.

Common Pitfalls

  • Start with count = 0, not 1. Seeding the count at 1 while candidate is already nums[0] counts the first element twice, and the vote never swings back: [9,2,2] returns 9 instead of 2.
  • Boyer-Moore only promises a correct answer when a majority genuinely exists. On input with no element past n/2 it returns whatever survived, so if the guarantee is not given, verify the candidate in a second pass.

Full Solution — all languages

class Solution:
    def majorityElement(self, nums):
        candidate = nums[0]
        count = 0
        for v in nums:
            if count == 0:
                candidate = v
                count = 1
            elif v == candidate:
                count += 1
            else:
                count -= 1
        return candidate
SensAI
Beta
Tap the mic to stop voice mode