Problem Statement

Majority Element

You are given a list of numbers called nums. One value shows up more than half the time. That value is called the majority element. Your job is to find it and return it. You can assume this value always exists, so you never have to handle a list where no value passes the halfway mark.

easyArrayHash TableArrays & HashingTime: O(n) · Space: O(1)

Signals to notice

element appears more than n/2 timesfind the majorityBoyer-Moore voting

Brute force first

Count every element with a hash map. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

The key insight

Boyer-Moore voting: maintain a candidate and counter. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

Trace it on nums=[2,2,1,1,1,2,2]

init: candidate=2, count=0
num=2: count==0 -> candidate=2; match -> count=1
num=2: match -> count=2
num=1: no match -> count=1
num=1: no match -> count=0 (candidate vote canceled)
num=1: count==0 -> candidate=1; match -> count=1
num=2: no match -> count=0
num=2: count==0 -> candidate=2; match -> count=1; return candidate=2

What must stay true

The majority element survives cancellation because it appears more than all others combined. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Shape of the loop

candidate = nums[0]; count = 0
for num in nums:
    if count == 0: candidate = num
    count += 1 if num == candidate else -1
return candidate

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Not knowing Boyer-Moore — the trick is that the majority element always wins the vote. The fix is usually to return to the meaning of each move, not just the steps themselves.

Arrays & Hashing Pattern