diff --git a/wizard-work/beam/majority_element.py b/wizard-work/beam/majority_element.py new file mode 100644 index 0000000..3d14f06 --- /dev/null +++ b/wizard-work/beam/majority_element.py @@ -0,0 +1,22 @@ +"""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 diff --git a/wizard-work/beam/test_majority_element.py b/wizard-work/beam/test_majority_element.py new file mode 100644 index 0000000..04b70a6 --- /dev/null +++ b/wizard-work/beam/test_majority_element.py @@ -0,0 +1,14 @@ +import unittest +from majority_element import majority + +class TestMajority(unittest.TestCase): + def test_basic(self): + self.assertEqual(majority([1,1,2]), 1) + self.assertEqual(majority([2,2,1,1,1]), 1) + self.assertIsNone(majority([1,2,3])) + self.assertIsNone(majority([])) + self.assertEqual(majority([5]), 5) + self.assertEqual(majority([1,1,1,2,2,2,2]), 2) + +if __name__ == "__main__": + unittest.main()