Skip to content

Commit a40644d

Browse files
committed
added algorithm to find majority element in the array using the boyer-moore algorithm
1 parent a71618f commit a40644d

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
def majority_element(arr: list[int]) -> int | None:
2+
"""
3+
Find the majority element in an array using the Boyer-Moore Voting Algorithm
4+
The majority element is the element that appears more than n/2 times (n is the size of the array)
5+
6+
Args:
7+
arr(list[int]): The input array
8+
9+
Returns:
10+
int | None: The majority element if it exists
11+
12+
Examples:
13+
>>> majority_element([3, 3, 4, 2, 4, 4, 2, 4, 4])
14+
4
15+
>>> majority_element([2, 2, 1, 1, 1, 2, 2])
16+
2
17+
>>> majority_element([1, 2, 3])
18+
None
19+
>>> majority_element([])
20+
None
21+
"""
22+
23+
count = 0
24+
majority = None
25+
26+
for num in arr:
27+
if count == 0:
28+
majority = num
29+
count = 1
30+
elif num == majority:
31+
count += 1
32+
else:
33+
count -= 1
34+
35+
if majority is not None and arr.count(majority) > len(arr) // 2:
36+
return majority
37+
return None
38+
39+
40+
if __name__ == "__main__":
41+
arr = [3, 3, 4, 2, 4, 4, 2, 4, 4]
42+
print("Majority element: ", majority_element(arr))

0 commit comments

Comments
 (0)