Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 51k
Expand file tree
/
Copy pathmajority_vote_algorithm.py
More file actions
Latest commit
38 lines (32 loc) · 1.2 KB
/
Copy pathmajority_vote_algorithm.py
File metadata and controls
38 lines (32 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
"""
This is Booyer-Moore Majority Vote Algorithm. The problem statement goes like this:
Given an integer array of size n, find all elements that appear more than ⌊ n/k ⌋ times.
We have to solve in O(n) time and O(1) Space.
URL : https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm
"""
fromcollectionsimportCounter
defmajority_vote(votes: list[int], votes_needed_to_win: int) ->list[int]:
"""
>>> majority_vote([1, 2, 2, 3, 1, 3, 2], 3)
[2]
>>> majority_vote([1, 2, 2, 3, 1, 3, 2], 2)
[]
>>> majority_vote([1, 2, 2, 3, 1, 3, 2], 4)
[1, 2, 3]
"""
majority_candidate_counter: Counter[int] =Counter()
forvoteinvotes:
majority_candidate_counter[vote] +=1
iflen(majority_candidate_counter) ==votes_needed_to_win:
majority_candidate_counter-=Counter(set(majority_candidate_counter))
majority_candidate_counter=Counter(
voteforvoteinvotesifvoteinmajority_candidate_counter
)
return [
vote
forvoteinmajority_candidate_counter
ifmajority_candidate_counter[vote] >len(votes) /votes_needed_to_win
]
if__name__=="__main__":
importdoctest
doctest.testmod()