Given an array
The majority element is the element that appears more than
Output: 3
Explanation: element 3 appeared 2 times and that is majority element.
Output: 2
Explanation: element 2 appeared 4 times and that is majority element.
Contents
Solution using a HashMap to store count of each number appearance Solution to follow-up question using 'Boyer-Moore' pattern searching algorithm
In this approach, we are going to iterate through elements of input array
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(n) since we are storing count mappping into a
Implementation details
In this approach, we are going to create two variables
This approach will work based on the fact that a majority element always exists (number that appears more than
-
When the
count is 0, we just updatecount = 1 andmax to current number. -
If the current number is same as
max then we will incrementcount . -
If the current number is not same as
max then we will decrementcount . -
Finally, just return
max .
Let's understand with an example, say
-
In the first step
count =0 , so we take number intomax = 2 andcount =1 . -
Next number is 3, and this is not same as
max that we got so far, so decrementcount , so it becomescount =0 . -
Next number is 2, and the
count =0 , so we updatemax =2 andcount =1 . -
Next number is 3, and this is not same as
max that we got so far, so decrementcount , so it becomescount =0 . -
Next number is 2, and the
count =0 , so we updatemax =2 andcount =1 . -
Now, notice that
max variable holds number2 , and that is our answer, so return that.
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(1).
Above implementations source code can be found at