Find the Majority Element | Set 3 (Bit Magic)

Pre-requisite: Majority Element, Majority Element | Set-2 (Hashing)

Given an array of size N, find the majority element. The majority element is the element that appears more than n/2 times in the given array.

Examples:



Input: {3, 3, 4, 2, 4, 4, 2, 4, 4}
Output: 4

Input: {3, 3, 6, 2, 4, 4, 2, 4}
Output: No Majority Element

Approach:

In this post, we solve the problem with the help of binary representation of the numbers present in the array.

The task is to find the element that appears more than n/2 times. So, it appears more than all other numbers combined.

So, we starting from LSB (least significant bit) of every number of the array, we count in how many numbers of the array it is set. If any bit is set in more than n/2 numbers, then that bit is set in our majority element.

The above approach works because for all other numbers combined the set bit count can’t be more than n/2, as the majority element is present more than n/2 times.

Lets see with the help of example

Input : {3, 3, 4, 2, 4, 4, 2, 4, 4}
Binary representation of the same are:

3 - 0 1 1
3 - 0 1 1
4 - 1 0 0
2 - 0 1 0
4 - 1 0 0
4 - 1 0 0
2 - 0 1 0
4 - 1 0 0
4 - 1 0 0
----------
  - 5 4 0 

Here n is 9, so n/2 = 4 and an only 3rd bit from right satisfy count>4 and hence set in majority element and all other bits are not set.

So, our majority element is 1 0 0, which is 4

But there more to it, This approach works when the majority element is present in the array. What if it is not present?
Let’s see with the help of this example:

Input : {3, 3, 6, 2, 4, 4, 2, 4}
Binary representation of the same are:

3 - 0 1 1
3 - 0 1 1
6 - 1 1 0
2 - 0 1 0
4 - 1 0 0
4 - 1 0 0
2 - 0 1 0
4 - 1 0 0
----------
  - 4 5 0 

Here n is 8, so n/2 = 4 and an only 2nd bit from right satisfy count>4 and hence set it should be set in majority element and all other bits not set.

So, our majority element according to this is 0 1 0, which is 2 But actually majority element is not present in the array. So, we do one more pass of the array, to make sure this element is present more than n/2 times.

Here is the implementation of the above idea

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
using namespace std;
  
void findMajority(int arr[], int n)
{
    // Number of bits in the integer
    int len = sizeof(int) * 8;
  
    // Variable to calculate majority element
    int number = 0;
  
    // Loop to iterate through all the bits of number
    for (int i = 0; i < len; i++) {
        int count = 0;
        // Loop to iterate through all elements in array
        // to count the total set bit
        // at position i from right
        for (int j = 0; j < n; j++) {
            if (arr[j] & (1 << i))
                count++;
        }
        // If the total set bits exceeds n/2,
        // this bit should be present in majority Element.
        if (count > (n / 2))
            number += (1 << i);
    }
  
    int count = 0;
  
    // iterate through array get
    // the count of candidate majority element
    for (int i = 0; i < n; i++)
        if (arr[i] == number)
            count++;
  
    // Verify if the count exceeds n/2
    if (count > (n / 2))
        cout << number;
    else
        cout << "Majority Element Not Present";
}
  
// Driver Program
int main()
{
  
    int arr[] = { 3, 3, 4, 2, 4, 4, 2, 4, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    findMajority(arr, n);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

class GFG 
{
    static void findMajority(int arr[], int n) 
    
        // Number of bits in the integer 
        int len = 32
      
        // Variable to calculate majority element 
        int number = 0
      
        // Loop to iterate through all the bits of number 
        for (int i = 0; i < len; i++) 
        
            int count = 0
            // Loop to iterate through all elements in array 
            // to count the total set bit 
            // at position i from right 
            for (int j = 0; j < n; j++) 
            
                if ((arr[j] & (1 << i)) != 0
                    count++; 
            
              
            // If the total set bits exceeds n/2, 
            // this bit should be present in majority Element. 
            if (count > (n / 2)) 
                number += (1 << i); 
        
      
        int count = 0
      
        // iterate through array get 
        // the count of candidate majority element 
        for (int i = 0; i < n; i++) 
            if (arr[i] == number) 
                count++; 
      
        // Verify if the count exceeds n/2 
        if (count > (n / 2)) 
            System.out.println(number); 
        else
            System.out.println("Majority Element Not Present"); 
    
      
    // Driver Code
    public static void main (String[] args) 
    
        int arr[] = { 3, 3, 4, 2, 4, 4, 2, 4, 4 }; 
        int n = arr.length; 
        findMajority(arr, n); 
    
}
  
// This code is contributed by AnkitRai01

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

def findMajority(arr, n):
      
    # Number of bits in the integer
    Len = 32
  
    # Variable to calculate majority element
    number = 0
  
    # Loop to iterate through 
    # all the bits of number
    for i in range(Len):
        count = 0
          
        # Loop to iterate through all elements 
        # in array to count the total set bit
        # at position i from right
        for j in range(n):
            if (arr[j] & (1 << i)):
                count += 1
                  
        # If the total set bits exceeds n/2,
        # this bit should be present in 
        # majority Element.
        if (count > (n // 2)):
            number += (1 << i)
  
    count = 0
  
    # iterate through array get
    # the count of candidate majority element
    for i in range(n):
        if (arr[i] == number):
            count += 1
  
    # Verify if the count exceeds n/2
    if (count > (n // 2)):
        print(number)
    else:
        print("Majority Element Not Present")
  
# Driver Code
arr = [3, 3, 4, 2, 4, 4, 2, 4, 4]
n = len(arr)
findMajority(arr, n)
  
# This code is contributed by Mohit Kumar

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

using System;
  
class GFG
{
    static void findMajority(int []arr, int n) 
    
        // Number of bits in the integer 
        int len = 32; 
      
        // Variable to calculate majority element 
        int number = 0; 
      
        // Loop to iterate through all the bits of number 
        for (int i = 0; i < len; i++) 
        
            int countt = 0; 
              
            // Loop to iterate through all elements 
            // in array to count the total set bit 
            // at position i from right 
            for (int j = 0; j < n; j++) 
            
                if ((arr[j] & (1 << i)) != 0) 
                    countt++; 
            
              
            // If the total set bits exceeds n/2, 
            // this bit should be present in majority Element. 
            if (countt > (n / 2)) 
                number += (1 << i); 
        
      
        int count = 0; 
      
        // iterate through array get 
        // the count of candidate majority element 
        for (int i = 0; i < n; i++) 
            if (arr[i] == number) 
                count++; 
      
        // Verify if the count exceeds n/2 
        if (count > (n / 2)) 
            Console.Write(number); 
        else
            Console.Write("Majority Element Not Present"); 
    
      
    // Driver Code
    static public void Main ()
    {
        int []arr = { 3, 3, 4, 2, 4, 4, 2, 4, 4 }; 
        int n = arr.Length; 
        findMajority(arr, n); 
    
}
  
// This code is contributed by @Tushi..

chevron_right


Output:

4

Time complexity : O(N*logN)
Space Complexity: O(1)



My Personal Notes arrow_drop_up

Completely in love with Data Structure and Algorithms and GeeksForGeeks provides me with the opportunity to write my own articles, review and improve articles of others thereby strengthening my skills and it makes spreading and improving knowledge more fun than it earlier was

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.





Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.