Given an integer array containing duplicates, return the majority element if present. A majority element appears more than n/2 times, where n is the array size.

For example, the majority element is 2 in array {2, 8, 7, 2, 2, 5, 2, 3, 1, 2, 2}.

Practice this problem

1. Brute-Force Solution

A naive solution is to count each element’s frequency in the first half of the array to check if it is the majority element. Following is the naive implementation:

The time complexity of the above solution is O(n2), where n is the size of the input.

 
We can improve worst-case time complexity to O(n.log(n)) by sorting the array and then perform a binary search for each element’s first and last occurrence. If the difference between first and last occurrence is more than n/2, the The majority element is found.

2. Linear-time Solution

We can use hashing to solve this problem in linear time. The idea is to store each element’s frequency in a map and return it if its frequency becomes more than n/2. If no such element is present, then the The majority element doesn’t exist in the array, and return -1.

Following is the implementation in C++, Java, and Python based on the above idea:

C++


Download  Run Code

Output:

The majority element is 2

Java


Download  Run Code

Output:

The majority element is 2

Python


Download  Run Code

Output:

The majority element is 2

 
The time complexity of the above solution is O(n) and requires O(n) extra space.

3. Boyer–Moore majority vote algorithm

We can find the majority element using linear time and constant space using the Boyer–Moore majority vote algorithm. The algorithm can be expressed in pseudocode as the following steps:

 Initialize an element m and a counter i = 0
 
 for each element x of the input sequence:
   if i = 0, then
     assign m = x and i = 1
   else
     if m = x, then assign i = i + 1
   else
     assign i = i – 1
 return m

The algorithm processes each element of the sequence, one at a time. When processing an element x,

  1. If the counter is 0, set the current candidate to x, and set the counter to 1.
  2. If the counter is non-zero, increment or decrement it according to whether x is a current candidate.

At the end of this process, if the sequence has a majority, it will be the element stored by the algorithm. If there is no majority element, the algorithm will not detect that fact and may output the wrong element. In other words, the Boyer–Moore majority vote algorithm produces correct results only when the majority element is present in the input.

 
The algorithm can be implemented as follows in C, Java, and Python. It is recommended to modify the algorithm to verify if the returned element is, in fact, a majority element or not.

C


Download  Run Code

Output:

The majority element is 2

Java


Download  Run Code

Output:

The majority element is 2

Python


Download  Run Code

Output:

The majority element is 2

References: Boyer–Moore majority vote algorithm – Wikipedia