Skip to content

Majority Value

Easy#counting#single-pass~15 min

The mission

Problem

One value in a list occupies more than half of all positions. Return that value. You may assume such a value always exists, so you never have to report failure, and the list is never empty.

Examples

Input:  nums = [3, 3, 4]
Output: 3
Why:    3 fills two of the three slots, which is more than half
Input:  nums = [2, 2, 1, 1, 2]
Output: 2
Why:    the majority value is not required to sit together
Input:  nums = [9]
Output: 9
Why:    edge case, the only value trivially owns more than half the list

Hints

0 / 3

Target time
O(n)
Target space
O(1)

Constraints

  • one value fills more than half the positions
  • the list is never empty

Stuck on the idea rather than the code? Majority Element covers it.

Python 3Ctrl+Enter runs
Custom test case