An optimal algorithm used to find the majority element, an element that has at least n / 2
occurrences.
If an element has at least n / 2
occurrences, all other elements will have less than n / 2
occurrences. If we can guarantee that the items given have a majority element that shows up at least n / 2
times, we’d only need to iterate thru the items once. Otherwise, we’d need a second traversal to ensure that the proposed majority element actually shows up at least n / 2
times.
Time complexity: , where = number of elements Space complexity:
Algorithm
- Select a candidate element. This can be initialized to
0
. - Initialize a counter to 0. This will keep track of the count of the candidate.
- Iterate thru the elements
- If the count is 0, set the current element as the candidate
- If the current element is equal to the candidate, increment the count by 1
- Otherwise decrement the count by 1
- If we’re not sure that there is a majority element (shows up at least
n / 2
times), then do a second pass thru the elements and check the count of the proposed candidate element. - Return the candidate element
Essentially incrementing the count will increase the priority of the winning ability of the current candidate element. Decrementing the count will decrease the priority of the winning ability of the current candidate element.