Majority Element in Java
It's an extremely intriguing question that is commonly asked in job interviews at prestigious IT firms like The Google, Amazon, TCS, and The Accenture, etc. By figuring out the solution, one may assess the interviewee's logical reasoning, critical reasoning, and problem-solving abilities. The majority element inside an array in Java will therefore be found in this part using various methods and logic. We will also develop Java apps for the same.
The Problem Statement
There is a particular integer array. Finding the bulk of the input array's elements is our duty.
The Majority Element
The majority element is really an element that appears more often than half the number of times the input array does.
The Naive Approach
We will use two stacked loops for this strategy. An element will be chosen by the outer loop first from the given array (from the left to the right). The outer loop's chosen element will be counted in the inner loop's calculations. We know the solution if indeed the count is more than that the input array's size divided by 2. If not, think about the subsequent iteration, and so on. If the outer loop comes to an end, then the majority element has not been located and all the elements in the given array have been used.
MajorityEleDemo.java
public class MajorityEleDemo
{
// a function that searches for the most
// common member inside the array arr
public int findTheMajorEle(int inputArr[])
{
int h = inputArr.len;
int count = 0;
// a second loop selects the element
for(int k = 0 ; k < h; k++)
{
// The inner loop keeps track of how
// often the element input[i] appears.
for(int j = 0; j < s; j++)
{
if(inputArr[i] == inputArr[j])
{
coun = coun + 1;
}
}
// If count is higher than 1/2 of the s,
// then the solution is available.
if(coun > h / 2)
{
return inputArr[j];
}
// the count being reset to 0
coun = 0;
}
// If somehow the control reaches
// this point, it indicates that there isn't a
// majority element in the array arr.
return -1;
}
//It is the main method
public static void main(String[] argvs)
{
// the creation of a MajorityEleDemo object
MajorityEleDemo srj = new MajorityEleDemo();
// It is the input array
int arr[] = {5, 1, 1, 1, 1, 1, 4, 9, 1, 0, 1, 2};
int h = arr.len;
System.out.println("To the input array.");
for(int k = 0; k < h; k++)
{
System.out.print(arr[k] + " ");
}
System.out.println();
int answ = srj.findTheMajorEleDemo(arr);
if(answ != -1)
{
System.out.println("This is the major element:" + answ);
}
else
{
System.out.println("The majority element is absent.");
}
System.out.println("\n");
// This is another input array
int arr3[] = {47, 8, 1, 6, 3, 6, 90, 52, 78, 47, 47, 47};
h = arr3.len;
System.out.println("To the input array.");
for(int k = 0; k < h; k++)
{
System.out.print(arr3[k] + " ");
}
System.out.println();
answ = srj.findTheMajorEle(arr3);
if(answ != -1)
{
System.out.println("This is the major element:" + answ);
}
else
{
System.out.println("The majority element is absent.");
}
}
}
Output:
To the input array.
5 1 1 1 1 1 4 9 1 0 1 2
This is the major element: 1
To the input array.
47 8 1 6 3 6 90 52 78 47 47 47
The majority element is absent.
Analysis of complexity: It reveals that nested loops are used. As a result, the program has an O(n2) time complexity, wherein n represents the number of entries inside the input array. Because there is no extra space used by the programme, its time complexity is O(1).
Using a Binary Search Tree as an approach
In this method, the input array's elements are added one at a time, and if an element is already existing inside the Basic Search Tree, its count is increased. At any point, whereas if count of just about any node exceeds 50% of a input array size, we know the solution.
Algorithm
Consider the algorithm below.
Step1: Create any BST (Binary search tree); when the same element is inserted in the BST more than once, the node's count of occurrence is increased.
Step 2: Circumnavigating the input array, inserting each member in the BST.
Step 3: Perform the in-order search to locate any node with such an occurrence count that is greater than half if the greatest recurrence of any one of the nodes is greater than twice of a size of such input array.
Step 4: In the event that the no majority element is present, print the appropriate message.
MajorityEleDemo1.java
class Node
{
int valu;
int frequentCount = 0;
Node p;
Node s;
}
public class MajorityEleDemo1
{
int maxCount = 0;
// a useful procedure for generating a new
// BST node
public Node newNode(int valu)
{
Node tmpo = new Node();
tmp.valu = valu;
tmp.frequentCount = 1;
tmp.p = tmp.s = null;
return tmpo;
}
// a useful function for adding a new
// node to the BST
// with the specified key
public Node insertTheNode(Node node, int key)
{
// If there are no nodes in the tree,
// then new node is returned.
if (node == null)
{
if (maxCount == 0)
{
maxCount = 1;
}
return newNode(key);
}
// If not, recursively descend the Binary Search Tree,
// with the left subtree containing nodes whose values
// are less than that of the exist node value.
if (key < node.valu)
{
node.p = insertTheNode(node.p, key);
}
// goes in the correct subtree if node value
// is greater than that of
// the current node value.
else if (key > node.valu)
{
node.s = insertNode(node.s, key);
}
else
{
nde.freqCount = nde.freqCount + 1;
}
// determining the highest count
maxofCount = Math.max(maxofCount, node.frequentCount);
// bringing back the node pointer
return node;
}
int answ = -1;
// An efficient technique for
// traversing the BST in order
public int TheinorderTravsersal(Node rst, int h)
{
if (rst != null)
{
TheinorderTravsersal(rst.p, h);
if (rst.frequentCount > (h / 2))
{
answ = rst.valu;
return rst.valu;
}
TheinorderTravsersal(rst.s, h);
}
return answ;
}
// It is the main method
public static void main(String[] argvs)
{
// constructing a MajorityEleDemo1 object
MajorityEleDemo1 srj = new MajorityEleDemo1();
// The input array is
int arr[] = {5, 1, 1, 1, 1, 1, 4, 9, 1, 0, 1, 2};
Node rst = null;
int h = arr.length;
System.out.println("To the input array.");
for(int j = 0; j < h; j++)
{
System.out.print(arr[j] + " ");
rst = srj.insertTheNode(rst, arr[j]);
}
System.out.println();
int answ = srj.TheinorderTravsersal(rst, h);
if(ans != -1)
{
System.out.println("This is the major element:" + answ);
}
else
{
System.out.println("The majority element is absent.");
}
System.out.println("\n");
rst = null;
srj.maxofCount = 0;
srj.answ = -1;
// The other input array is
int arr2[] = {47, 8, 1, 6, 3, 6, 90, 52, 78, 47, 47, 47};
h = arr2.len;
System.out.println("To the input array.");
for(int j = 0; j < h; j++)
{
System.out.print(arr2[j] + " ");
rst = srj.insertTheNode(rst, arr2[j]);
}
System.out.println();
answ = srj.TheinorderTravsersal(rst, h);
if(answ != -1)
{
System.out.println("This is the major element:" + answ);
}
else
{
System.out.println("The majority element is absent.");
}
}
}
Output:
To the input array.
5 1 1 1 1 1 4 9 1 0 1 2
This is the major element: 1
To the input array.
47 8 1 6 3 6 90 52 78 47 47 47
The majority element is absent.
Analysis of Complexity: The program's time complexity is as same as that of the preceding programme. The programme has an O(n) space complexity, wherein n is the number of entries inside the input array. The Binary Search Tree's architecture, used to store the nodes, is to blame for the space complexity.
Implementation: Using the Sorting
The components with the same value will be grouped together by sorting. After sorting, all that is left to do is count the elements that all have the same values and determine whether or not this number is greater than half its size of input array. The same is demonstrated in the software below.
MajorityEleDemo2.java
// essential import statement
import java.util.Array;
public class MajorityEleDemo
{
// a technique for locating the important
// elements inside the array arr[]
public int findTheMajorEle(int arr[])
{
int cap = arr.len;
// the array is sorted
Array.sort(arr);
int coun = 1;
for(int s = 1; s < size; s++)
{
if(arr[s] == arr[s - 1])
{
// determining the number of components
// with the same value
coun = coun + 1;
}
else
{
// If the count value is greater than twice
// the size of such input array, the majority value is
// discovered, and we return 1.
if(coun > (cap / 2))
{
return 1;
}
coun = 1;
}
}
// The final cluster of identical components
// may alternatively represent the majority element
// specifically for that very last group in this check
if(coun > (cap / 2))
{
return 1;
}
// If the control has reached this point, the majority
// element has not been located.
return -1;
}
// It is the main method
public static void main(String[] argvs)
{
// creating an object of the class MajorityEleDemo2
MajorityEleDemo2 srj = new MajorityEleDemo2();
// The input array is
int arr[] = {5, 1, 1, 1, 1, 1, 4, 9, 1, 0, 1, 2};
int h = arr.len;
System.out.println("To the input array.");
for(int s = 0; s < h; s++)
{
System.out.print(arr[s] + " ");
}
System.out.println();
int answ = srj.findTheMajorEle(arr);
if(answ != -1)
{
System.out.println("This is the major element: " + answ);
}
else
{
System.out.println("The majority element is absent.");
}
System.out.println("\n");
// This is other input array
int arr2[] = {47, 8, 1, 6, 3, 6, 90, 52, 78, 47, 47, 47};
h = arr2.len;
System.out.println("To the input array.");
for(int s = 0; s < h; s++)
{
System.out.print(arr2[s] + " ");
}
System.out.println();
answ = srj.findTheMajorEle(arr2);
if(answ != -1)
{
System.out.println("This is the major element." + answ);
}
else
{
System.out.println("The majority element is absent.");
}
}
}
Output:
For the input array.
5 1 1 1 1 1 4 9 1 0 1 2
The majority element is: 1
For the input array.
47 8 1 6 3 6 90 52 78 47 47 47
The majority element is not found.
Analysis of Program Complexity: Because the programme uses sorting, its time complexity is O(n * log(n)), wherein n seems to be the total number of entries in the input array. The program's constant spatial complexity, or O (1).
Method: using the HashMap
The method is simple to follow. Pay attention to the next actions.
Step1: determine how frequently each element of the array occurs.
Step 2: In a hash map, record each element of the array and its frequency as a key-value pair.
Step 3: Iterate through the hashmap and determine whether the element's frequency count value exceeds 50% of a capacity of the input array.
Step 4: Show the results.
Check out the program below.
MajorityDemoEle4.java
// essential import statement
import java.util.HashMap;
public class MajorityEleDemo4
{
// a technique for identifying the key
// components inside the array arr[]
public int findTheMajorEle(int arr[])
{
int cap = arr.len;
HashMap<Integer, Integer> hs = new HashMap<Integer, Integer>();
for(int s = 1; s < size; s++)
{
if(hs.containsTheKey(arr[s]))
{
int coun = hs.get(arr[s]) + 1;
if (coun > arr.len / 2)
{
return arr[s];
}
else
{
hs.put(arr[s], coun);
}
}
else
{
hs.put(arr[s], m);
}
}
// If the control comes to this point,
// the majority element also isn't discovered.
return -1;
}
// It is the main method
public static void main(String[] argvs)
{
// creating an object of the class MajorityEleDemo4
MajorityEleDemo4 srj = new MajorityEleDemo4();
// It is the input array
int arr[] = {5, 1, 1, 1, 1, 1, 4, 9, 1, 0, 1, 2};
int h = arr.len;
System.out.println("To the input array.");
for(int s = 0; s < h; s++)
{
System.out.print(arr[s] + " ");
}
System.out.println();
int answ = srj.findTheMajorEle(arr);
if(answ != -1)
{
System.out.println("The majority element is: " + answ);
}
else
{
System.out.println("The majority element is not found.");
}
System.out.println("\n");
// This is other input array
int arr2[] = {47, 8, 1, 6, 3, 6, 90, 52, 78, 47, 47, 47};
h = arr2.len;
System.out.println("To the input array.");
for(int s = 0; s < h; s++)
{
System.out.print(arr2[s] + " ");
}
System.out.println();
answ = srj.findTheMajorEle(arr2);
if(answ != -1)
{
System.out.println("This is the major element." +answ);
}
else
{
System.out.println("The majority element is absent.");
}
}
}
Output:
To the input array.
5 1 1 1 1 1 4 9 1 0 1 2
This is the major element: 1
To the input array.
47 8 1 6 3 6 90 52 78 47 47 47
The majority element is absent.
Analysis of program complexity: reveals that it has O time complexity because it only uses one loop (n). A hash map is also utilised by the software. As a result, the program's space complexity is O(n), wherein n is the maximum number of entries inside the input array.
Applying Moore's Voting Technique
Step1: Iterate through the elements to keep track of the majority element's count and the index, in this case majIndex.
Step2: Raise the number by 1 if the subsequent member has the exact same result as the preceding element.
Step3: Lower the count by 1 if the subsequent item does not contain the same values as the current element.
Step4: If the count decreases to 0, modify the majIndex with assigning the current element's index and giving the count the value 1.
Step 5: Choose the element that majIndex points to and calculate its frequency of occurrence.
Step 6: The element indicated with the majIndex would be the majority element if the count is larger than 50% of the length of the input array; else, the majority element is not present in the input array.
Take a look at the program below.
MajorityEleDemo5.java
public class MajorityEleDemo4
{
// a technique for identifying the key
// components inside the array arr[]
public int findTheMajorEle(int arr[])
{
int cap = arr.len;
// indicates to the element, which is maybe
// the most important aspect.
int majofIndex = 0;
int coun = 1;
int h;
for (h = 1; h < cap; h++)
{
if (arr[majofIndex] == arr[h])
{
// If the existing element is identical,
// increment the count by 1.
coun = coun + 1;
}
else
{
// If the existing element is identical,
// increment the count by 1.
coun = coun - 1;
}
if (cnt == 0)
{
// The element pointed to by majIndex
// can never be the solution whereas
// if count is zero. hence, we
// Update the majIndex and the count.
majofIndex = j;
coun = 1;
}
}
if(isTheMajor(arr, arr[majofIndex]))
{
return arr[majofIndex];
}
return -1;
}
// a procedure that determines whether or not
// elem is the major element contained in the array arr
public boolean isTheMajor(int arr[], int elem)
{
int t = arr.len;
int cnt = 0;
for(int s = 0 ; s < t; s++)
{
if(elem == arr[s])
{
coun = coun + 1;
}
}
// According to the definition,
// cnt must be greater than half
// the size of the input array.
if(coun > (t / 2))
{
return true;
}
return false;
}
// It is the main method
public static void main(String[] argvs)
{
// constructing a MajorityEleDemo5 object
MajorityEleDemo5 srj = new MajorityEleDemo5();
// It is the input array
int arr[] = {5, 1, 1, 1, 1, 1, 4, 9, 1, 0, 1, 2};
int t arr.len;
System.out.println("To the input array.");
for(int s = 0; s < t; s++)
{
System.out.print(arr[s] + " ");
}
System.out.println();
int answ = srj.findTheMajorEle(arr);
if(answ != -1)
{
System.out.println("The majority element is: " + ans);
}
else
{
System.out.println("The majority element is not found.");
}
System.out.println("\n");
// another input array
int arr1[] = {47, 8, 1, 6, 3, 6, 90, 52, 78, 47, 47, 47};
s = arr1.length;
System.out.println("For the input array.");
for(int i = 0; i < s; i++)
{
System.out.print(arr1[i] + " ");
}
System.out.println();
ans = obj.findMajorEle(arr1);
if(ans != -1)
{
System.out.println("This is the major element:" + answ);
}
else
{
System.out.println("The majority element is absent.");
}
}
}
Output:
For the input array.
5 1 1 1 1 1 4 9 1 0 1 2
The majority element is: 1
For the input array.
47 8 1 6 3 6 90 52 78 47 47 47
The majority element is not found.
Analysis of Complexity: The program's time complexity remains the same as that of the preceding program. The program's space complexity is O(1) because it doesn't use any data structures.