Files
troupe-standup/wizard-work/beam/majority_element.py
T

23 lines
536 B
Python

"""Boyer-Moore majority vote: element appearing > n/2 times, or None."""
from __future__ import annotations
from typing import Any, Iterable, Optional
def majority(nums: Iterable[Any]) -> Optional[Any]:
arr = list(nums)
cand = None
count = 0
for x in arr:
if count == 0:
cand = x
count = 1
elif x == cand:
count += 1
else:
count -= 1
if not arr:
return None
if arr.count(cand) > len(arr) // 2:
return cand
return None