Skip to content

Commit e3df725

Browse files
authored
Add majority_element function using Boyer-Moore algorithm
Implement Boyer-Moore Voting Algorithm to find majority element.
1 parent 0f5d1e4 commit e3df725

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
def majority_element(nums: list[int]) -> int:
2+
"""
3+
Find majority element using Boyer-Moore Voting Algorithm
4+
https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm
5+
6+
>>> majority_element([3, 3, 4])
7+
3
8+
>>> majority_element([2, 2, 1, 1, 2, 2, 2])
9+
2
10+
"""
11+
12+
if not nums:
13+
raise ValueError("List cannot be empty")
14+
15+
candidate = None
16+
count = 0
17+
18+
for num in nums:
19+
if count == 0:
20+
candidate = num
21+
count += (1 if num == candidate else -1)
22+
23+
return candidate

0 commit comments

Comments
 (0)