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 – Sorting

Assuming the majority exists and since the majority always takes more than half of space, the middle element is guaranteed to be the majority. Sorting array takes O(nlog(n)). So the time complexity of this solution is nlog(n).

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

Java Solution 2 – Majority Vote Algorithm

This problem can be solved in time of O(n) with constant space complexity. The basic idea is that the majority element can negate all other element’s count.

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

15 thoughts on “LeetCode – Majority Element (Java)”

  1. Wow, amazing O(1) space complexity solution.

    The for loop can be replaced with foreach loop. The index isn’t important.

    for (int num : nums) {...

  2. Request to clear confusions
    There may exist more than 1 majority element in an array?
    For the array A = {2,3,2,3,2,3,2,3}, there r 2 majority elements, so one should output any one or should output both?
    [If an element appears exactly n/2 times, then it is not majority element(the majority element needs to appear more than n/2 times)]


  3. 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));
    }
    }

  4. 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.)”

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

  6. 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 ) {

    }

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

  8. 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];
    }
    }

Leave a Comment