|
| 1 | +""" |
| 2 | +This is Booyer-Moore Majority Vote Algorithm. The problem statement goes like this: |
| 3 | +Given an integer array of size n, find all elements that appear more than ⌊ n/k ⌋ times. |
| 4 | +We have to solve in O(n) time and O(1) Space. |
| 5 | +URL : https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm |
| 6 | +""" |
| 7 | +from collections import Counter |
| 8 | + |
| 9 | + |
| 10 | +def majority_vote(votes: list[int], votes_needed_to_win: int) -> list[int]: |
| 11 | + """ |
| 12 | + >>> majority_vote([1, 2, 2, 3, 1, 3, 2], 3) |
| 13 | + [2] |
| 14 | + >>> majority_vote([1, 2, 2, 3, 1, 3, 2], 2) |
| 15 | + [] |
| 16 | + >>> majority_vote([1, 2, 2, 3, 1, 3, 2], 4) |
| 17 | + [1, 2, 3] |
| 18 | + """ |
| 19 | + majority_candidate_counter: Counter[int] = Counter() |
| 20 | + for vote in votes: |
| 21 | + majority_candidate_counter[vote] += 1 |
| 22 | + if len(majority_candidate_counter) == votes_needed_to_win: |
| 23 | + majority_candidate_counter -= Counter(set(majority_candidate_counter)) |
| 24 | + majority_candidate_counter = Counter( |
| 25 | + vote for vote in votes if vote in majority_candidate_counter |
| 26 | + ) |
| 27 | + return [ |
| 28 | + vote |
| 29 | + for vote in majority_candidate_counter |
| 30 | + if majority_candidate_counter[vote] > len(votes) / votes_needed_to_win |
| 31 | + ] |
| 32 | + |
| 33 | + |
| 34 | +if __name__ == "__main__": |
| 35 | + import doctest |
| 36 | + |
| 37 | + doctest.testmod() |
0 commit comments