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

Majority Element

On a phone? Coding is easier on a laptop, and your draft saves in this browser. Meanwhile: quiz this topic or fight a boss.

easy ~15 min

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

An army of minions marches past you, each wearing a banner number. More than half of them (strictly more than len(minions) / 2) carry the same banner: that's 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.

Aim for one pass and O(1) extra memory: no dictionary of counts, no sorting. Keep one "champion" and a power counter. The performance test runs on a million minions.

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

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