# Majority Element in Java

JavaServer Side ProgrammingProgramming

Let’s suppose we have given an array of integers. The task is to find the index of a particular element in the given array. For example,

Input-1

N = 8
A[ ] = { 1,2,4,3,3,1,1,5}

Output

1

Explanation − In the given array of integers, the most appearing number is ‘1’. Thus the output is ‘1’.

Input-2

N = 6
A[ ] = {1,5,4,4,1,1}

Output

1

Explanation − In the given array of integers, the most appearing number is ‘1’. Thus we can return the output ‘1’.

## Approach to solve this problem

The given array contains multiple integers in which we have to find the most frequent element present in the array. To solve this problem in linear time O(n) and Linear Space O(n) we can use the approach of a hashmap.

In this approach, we will create an unordered map(STL Library) consist of key-value pair in which the key will be an element and the Value will be the occurrence of the element. While traversing through the map we will find the maximum occurrence of the number and return the number as Output.

• Take Input an array of size N

• An Integer function maxOccurrence(int A[], int size) takes an array and its size as an input and returns the numbers with maximum frequency.

• Creating a hashmap of all the elements of the array by taking the key as an element and value as its frequency.

• Iterating over the map and checking if any of the elements having the most frequency then return the result as the number. Otherwise, if there is not any number present in the array then return ‘-1’.

## Example

import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
class Majority_Element{
public static int checkMajorityElement(int arr[], int N){
Map<Integer, Integer> mp = new HashMap<Integer, Integer>();
for (int i = 0; i < N; i++){
if (mp.containsKey(arr[i]))
mp.put(arr[i], mp.get(arr[i]) + 1);
else
mp.put(arr[i], 1);
}
for (Map.Entry<Integer, Integer> entry : mp.entrySet()){
if (entry.getValue() > (N / 2))
return entry.getKey();
}
return -1;
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of array:");
int N = 6;
int arr[] = {2,1,1,2,2,2};
System.out.println("Enter elements of array:");
for (int i = 0; i < N; i++)
arr[i] = sc.nextInt();
int ans = checkMajorityElement(arr, N);
if (ans != -1)
System.out.println("Majority Element is: " + ans);
else
System.out.println("No majority element in array");
}
}

## Output

Running the above code will generate the output as,

Enter size of array: 6
Enter elements of array: 2 1 1 2 2 2
Majority Element is: 2
Published on 05-Feb-2021 07:57:57