Moore's Voting Algorithm
Problem¶
To find the majority element in an array. Majority element is the one which appear more than \(\lfloor n / 2 \rfloor\) times in an array.
Algorithm¶
- If the majority element is
xthen,count(x) - count(any other element) > 0. - Assign
count = 0andcandidatewhich keeps track of majority element. - Run a loop through array, if we face same element as
candidate, increasecountby 1. - Else, decrease the
countby 1. - If
countbecomes 0, updatecandidateby current element.
Code¶
- Time Complexity = \(O(N)\)
- Space Complexity = \(O(1)\)