Find the majority element in array

finding majority element in an array divide and conquer
majority element ii
majority element - leetcode
majority element interviewbit
check if a number is majority element in a sorted array - leetcode
find majority element in an array python
majority element bit manipulation
majority element divide and conquer python

The majority element is the element that occurs more than half of the size of the array.

How to find the majority element in an array in O(n)?

Example input:

{2,1,2,3,4,2,1,2,2}

Expected output:

2

The majority element (if it exists) will also be the median. We can find the median in O(n) and then check that it is indeed a valid majority element in O(n). More details for implementation link

Majority Element, Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the array is​  The first step gives the element that may be majority element in the array. If there is a majority element in an array, then this step will definitely return majority element, Check if the element obtained from above step is majority element.This step is necessary as we are not always sure that

// returns -1 if there is no element that is the majority element, otherwise that element

// funda :: if there is a majority element in an array, say x, then it is okay to discard 
// a part of that array that has no majority element, the remaining array will still have
// x as the majority element

// worst case complexity :  O(n)

int findMajorityElement(int* arr, int size) { 
    int count = 0, i, majorityElement;
    for (i = 0; i < size; i++) {
        if (count == 0)
            majorityElement = arr[i];
        if (arr[i] == majorityElement) 
            count++;
        else
            count--;
    }
    count = 0;
    for (i = 0; i < size; i++)
        if (arr[i] == majorityElement)
            count++;
    if (count > size/2)
        return majorityElement;
    return -1;
}

Find majority element in an array (Boyer–Moore majority vote , Find majority element in an array (Boyer–Moore majority vote algorithm) Given an array of integers containing duplicates, return the majority element in an array if present. A majority element appears more than n/2 times where n is the size of the array. Given an array of integers containing duplicates, return the majority element in an array if present. A majority element appears more than n/2 times where n is the size of the array. For example, the majority element is 2 in the array {2, 8, 7, 2, 2, 5, 2, 3, 1, 2, 2}

It is sad to see that in 5 years no one has written a proper explanation for this problem.

This is a standard problem in streaming algorithms (where you have a huge (potentially infinite) stream of data) and you have to calculate some statistics from this stream, passing through this stream once.


Clearly you can approach it with hashing or sorting, but with a potentially infinite stream you can clearly run out of memory. So you have to do something smart here.


The majority element is the element that occurs more than half of the size of the array. This means that the majority element occurs more than all the other elements combined. That is, if you count the number of times the majority element appears, and subtract the number of occurrences of all the other elements, you will get a positive number.

So if you count the occurrences of some element, and subtract the number of occurrences of all other elements and get the number 0 - then your original element can't be a majority element. This is the basis for a correct algorithm:

Declare two variables, counter and possible_element. Iterate the stream, if the counter is 0 - your overwrite the possible element and initialize the counter, if the number is the same as possible element - increase the counter, otherwise decrease it. Python code:

def majority_element(arr):
    counter, possible_element = 0, None
    for i in arr:
        if counter == 0:
            possible_element, counter = i, 1
        elif i == possible_element:
            counter += 1
        else:
            counter -= 1

    return possible_element

It is clear to see that the algorithm is O(n) with a very small constant before O(n) (like 3). Also it looks like the space complexity is O(1), because we have only three variable initialized. The problem is that one of these variables is a counter which potentially can grow up to n (when the array consists of the same numbers). And to store the number n you need O(log (n)) space. So from theoretical point of view it is O(n) time and O(log(n)) space. From practical, you can fit 2^128 number in a longint and this number of elements in the array is unimaginably huge.

Also note that the algorithm works only if there is a majority element. If such element does not exist it will still return some number, which will surely be wrong. (it is easy to modify the algorithm to tell whether the majority element exists)

History channel: this algorithm was invented somewhere in 1982 by Boyer, Moore and called Boyer–Moore majority vote algorithm

How to find the majority element in an array, How do you find the majority element in an array? C Program to Find Majority Element of Array Count of frequency of each element of array using two for loop. Outer for loop will fix one element (let's say K) and inner for loop will count the occurrences of K in inputArray. If count of K is more than N/2 then K is a majority element. If we don't

Majority Element:

A majority element in an array A[] of size n is an element that appears more than n/2 times (and hence there is at most one such element).

Finding a Candidate:

The algorithm for first phase that works in O(n) is known as Moore’s Voting Algorithm. Basic idea of the algorithm is if we cancel out each occurrence of an element e with all the other elements that are different from e then e will exist till end if it is a majority element.

findCandidate(a[], size)
1.  Initialize index and count of majority element
     maj_index = 0, count = 1
2.  Loop for i = 1 to size – 1
    (a)If a[maj_index] == a[i]
        count++
    (b)Else
        count--;
    (c)If count == 0
        maj_index = i;
        count = 1
3.  Return a[maj_index]

Above algorithm loops through each element and maintains a count of a[maj_index], If next element is same then increments the count, if next element is not same then decrements the count, and if the count reaches 0 then changes the maj_index to the current element and sets count to 1. First Phase algorithm gives us a candidate element. In second phase we need to check if the candidate is really a majority element.

Second phase is simple and can be easily done in O(n). We just need to check if count of the candidate element is greater than n/2.

Read geeksforgeeks for more details

How to Reverse Array in Place in Java? Solution With , You are given an array A[] consisting of n elements. You need to find and return the number which appears more than n/2 times. Find the majority element from the sorted array Given a sorted array, we need to find if a given x is a majority element. Majority element: Number occurring more than half the size of the array.

Time:O(n)

Space:O(n)

Walk the tree and count the occurrence of elements in a hash table.

Time:O(n lg n) or O(n*m)(depends on the sort used)

space:(1)

sort the array then count occurrences of the elements.

The interview correct answer: Moore’s Voting Algorithm

Time: O(n)

Space:O(1)

Walk the list compare the current number vs current best guess number. If the number is equal to the current best guess number increment a counter, otherwise decrement the counter and if the counter hits zero replace the current best guess number with the current number and set the counter to 1. When you get to the end the current best guess is the Candidate number, walk the list again just counting instances of the candidate. If the final count is greater than n/2 then it is the majority number otherwise there isn't one.

Find the majority element in an array, The majority element is an element in an array that occurs more than (size/2) times in an array (where size​ is the number of elements stored in an array). svg​  Write a program in C to find the majority element of an array. A majority element in an array A[] of size n is an element that appears more than n/2 times (and hence there is at most one such element).

Find the majority element in array, The majority element (if it exists) will also be the median. We can find the median in O(n) and then check that it is indeed a valid majority  The majority element is the element that occurs more than half of the size of the array. Algorithm below loops through each element and maintains a count of a[maj_index], If next element is same then increments the count, if next element is not same then decrements the count, and if the count reaches 0 then changes the maj_index to the current element and sets count to 1.

Find Majority Element in an Array, Problem: Given an array of size n, find the element which occurs more than n/2 times. This Duration: 5:45 Posted: Sep 1, 2015 Check for Majority Element in a sorted array Question: Write a C function to find if a given integer x appears more than n/2 times in a sorted array of n integers. Basically, we need to write a function say isMajority() that takes an array (arr[] ), array’s size (n) and a number to be searched (x) as parameters and returns true if x is a majority element (present more than n/2 times).

Majority Element in an array (Algorithm), Find the majority element in an array. Number of occurrences of that element must be greater Duration: 4:12 Posted: May 3, 2017 Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the array is non-empty and the majority element always exist in the array. Example 1: Input: [3,2,3] Output: 3. Example 2: Input: [2,2,1,1,1,2,2] Output: 2

Comments
  • Possible duplicate stackoverflow.com/questions/1191740/… although that question gaurantees the number occurs exactly N/2 times, this one says more than N/2.
  • For a proper explanation of this classical problem see my answer
  • Technically correct, but that O(N) has a very high constant factor.
  • @marcog Indeed. But when the interviewer rejects the best solution, you have to get creative :)
  • There are better linear time solutions. Read the duplicates in the comments above.
  • @marcog The two links I saw either mentions OP's algorithm itself or a probabilistic algorithm. Neither would've been acceptable in this situation.
  • The problem with this solution is that it requires the additional assumption that there is a total order on the elements. Although this is satisfied in the example with integers, in general elements are not necessarily comparable. There is a solution which requires only testing for equality, not order.
  • This is clearly the best solution. It is a special case of a stream counting algorithm, where only one element is tracked. (You can use a collection of n "majority elements" to find any element that constitutes 1 / (n + 1) or more of the elements. For example, with 9 majority elements, you find any element that occurs at least 10% of the time.
  • for an input array with {2,1,2,4,1,2}, shouldn't this method return 2. but it is returning -1.
  • @brainstorm: In an array of size 6, the majority element must appear at least 4 times. In your array, "2" only appears 3 times.
  • This is Moore’s Voting Algorithm, should be attributed properly.
  • what if the majority is -1?