Find the Majority Element | Set 3 (Bit Magic) - GeeksforGeeks

12 Feb, 2022
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++
Java
Python3
C#
Javascript
#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 Programint main(){     int arr[] = { 3, 3, 4, 2, 4, 4, 2, 4, 4 };    int n = sizeof(arr) / sizeof(arr[0]);    findMajority(arr, n);    return 0;}
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
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 Codearr = [3, 3, 4, 2, 4, 4, 2, 4, 4]n = len(arr)findMajority(arr, n) # This code is contributed by Mohit Kumar
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..
<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 Codelet arr = [ 3, 3, 4, 2, 4, 4, 2, 4, 4 ];let n = arr.length; findMajority(arr, n); // This code is contributed by decode2207 </script>
4
 
Time complexity : O(N) Space Complexity: O(1) 
mohit kumar 29
ankthon
jit_t
akd27
decode2207
sagar0719kumar
setBitCount
Arrays
Bit Magic
Arrays
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Trapping Rain Water
Reversal algorithm for array rotation
Program to find sum of elements in a given array
Building Heap from Array
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Count set bits in an integer
Cyclic Redundancy Check and Modulo-2 Division