Open In App

Find majority element using Bit Magic

Improve
Improve
Like Article
Like
Save
Share
Report

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++




#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;
}


Java




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


Python3




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


C#




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 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 (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..


Javascript




<script>
 
function findMajority(arr, n)
{
     
    // Number of bits in the integer
    let len = 32;
   
    // Variable to calculate majority element
    let number = 0;
   
    // Loop to iterate through all
    // the bits of number
    for(let i = 0; i < len; i++)
    {
        let countt = 0;
           
        // Loop to iterate through all elements
        // in array to count the total set bit
        // at position i from right
        for(let 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 > parseInt(n / 2, 10))
            number += (1 << i);
    }
   
    let count = 0;
   
    // Iterate through array get
    // the count of candidate
    // majority element
    for(let i = 0; i < n; i++)
        if (arr[i] == number)
            count++;
   
    // Verify if the count exceeds n/2
    if (count > parseInt(n / 2, 10))
        document.write(number);
    else
        document.write("Majority Element Not Present");
}
 
// Driver Code
let arr = [ 3, 3, 4, 2, 4, 4, 2, 4, 4 ];
let n = arr.length;
 
findMajority(arr, n);
 
// This code is contributed by decode2207
 
</script>


Output: 

4

 

Time complexity: O(N*logN) Where N is the number of elements present in the array, logN time is taken by the number of bits of an integer and, N time is taken to iterate all the elements of the array. So Time Complexity is O(len*N), which can be written in the form of N like this O(NlogN).
Auxiliary Space: O(1)



Last Updated : 09 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads