LeetCode – Majority Element (Java)

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. (assume that the array is non-empty and the majority element always exist in the array.)

Java Solution 1 - Naive

We can sort the array first, which takes time of nlog(n). Then scan once to find the longest consecutive substrings.

public class Solution {
    public int majorityElement(int[] num) {
        if(num.length==1){
            return num[0];
        }
 
        Arrays.sort(num);
 
        int prev=num[0];
        int count=1;
        for(int i=1; i<num.length; i++){
            if(num[i] == prev){
                count++;
                if(count > num.length/2) return num[i];
            }else{
                count=1;
                prev = num[i];
            }
        }
 
        return 0;
    }
}

Java Solution 2 - Much Simpler

Thanks to SK. His/her solution is much efficient and simpler.
Since the majority always take more than a half space, the middle element is guaranteed to be the majority. Sorting array takes nlog(n). So the time complexity of this solution is nlog(n). Cheers!

public int majorityElement(int[] num) {
	if (num.length == 1) {
		return num[0];
	}
 
	Arrays.sort(num);
	return num[num.length / 2];
}

Java Solution 3 - Linear Time Majority Vote Algorithm

public int majorityElement(int[] nums) {
    int result = 0, count = 0;
 
    for(int i = 0; i<nums.length; i++ ) {
        if(count == 0){
            result = nums[ i ];
            count = 1;
        }else if(result == nums[i]){
           count++;
        }else{
           count--;
        }
    }
 
    return result;
}

Reference:
A Linear Time Majority Vote Algorithm

Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • arnavawasthi


    public class MajorityElement {

    /**
    * Why this simple solution should work?
    * Theory: Either majority element will be the first element or there will at least one instance where at least two of them will
    * be at consecutive indices.
    * - When odd number of elements and there is a different number between each pair. One of the majority element will be at 0th pos.
    * - In all other cases, two or more of them will have to be on consecutive indices.
    * @param inputArr
    * @return
    */
    public static int solution(int[] inputArr){
    int majorityElem = inputArr[0];
    for(int i = 0; i < inputArr.length-1; i++){
    if(inputArr[i] == inputArr[i+1]){
    majorityElem = inputArr[i];
    }
    }

    return majorityElem;
    }

    public static void main(String[] args) {
    int a[] = new int[]{2,1,2,3,2,1,2};
    System.out.println(solution(a));
    }
    }

  • Solved this in C, three different methods
    http://algorithmsandme.in/2016/02/majority-element-in-an-array/

  • Maxim Rubis

    Your inputs are not correct, because there is no majority element in them.

    “The majority element is the element that appears more than ⌊ n/2 ⌋ times. (assume that the array is non-empty and the majority element always exist in the array.)”

  • Chaitra Deshpande

    Solution 2(Much Simpler) does not work for all inputs.
    Ex 1 : {2,2,2,2,6,7,4,4}; Ans :4
    Ex 2: {7,7,7,3,4,4,2,2}; Ans : 4
    and many more

  • Kyle

    Just iterate till end either to left or right.

  • vvicazz

    What if majority element is not present ? In that case your program will return wrong element.

  • Han Wang

    It’s a nice solution. But it requires O(N) extra space.

  • Radhika

    There is a standard O(n) algorithm for solving this problem. Its known as Moors’s Voting algorithm. The implementation for the same is given below

    int Maj( int [] a, int n ) {

    }

  • jason zhang

    Super!

  • jason zhang

    should be a special quickSelect problem

  • Puneet

    How about this? O(n) ..

    private static int returnMajorityElement(int[] array) {
    HashMap arrayElementsCounts = new HashMap();
    for (int i = 0; i < array.length; i++) {
    int elementCount = 1;
    if (arrayElementsCounts.containsKey(array[i])) {
    elementCount = arrayElementsCounts.get(array[i]) + 1;
    }

    arrayElementsCounts.put(array[i], elementCount);
    }
    // iterate arrayElementsCounts to find the majorityElement
    Iterator iterateArrayElementsCounts = arrayElementsCounts.entrySet().iterator();
    while (iterateArrayElementsCounts.hasNext()) {
    Map.Entry entry = (Map.Entry) iterateArrayElementsCounts.next();
    if (entry.getValue() > (array.length / 2)) { // return majorityElement
    return entry.getKey();
    }
    }

    // majority element doesn’t exist
    return 0;
    }

  • ryanlr

    Great solution!

  • SK

    It can be simplified. After sorting the array, the majority of the element should be in the middle of the array [or one less from the middle]. Because majority element always more than n/2.

    public class Solution {
    public int majorityElement(int[] num) {
    if(num.length==1){
    return num[0];
    }

    Arrays.sort(num);

    return num[num.length/2];
    }
    }