progress

~/problems / Arrays & hashing / Hash maps and counting

Majority Element

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

Write majority(minions: list[int]) -> int.

An army of minions marches past, each wearing a banner number. Strictly more than half carry the same banner: the secret boss's army. Return its banner number.

Example: minions = [4, 9, 4, 4, 2, 4] gives 4 (four of six); [7] gives 7.

Constraints: 1 <= len(minions) <= 10^6, and a majority banner always exists.

Counting with a dictionary works. The real challenge is one pass and O(1) extra memory: keep one "champion" and a power counter. ⭐ Bonus: a speed test with a million minions earns a star for one pass.

Topic: Hash maps and counting. Counter/defaultdict, complement lookups, prefix-sum + hash map.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc