×

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.


Related Topics

Java String substring() method

Java String substring() method returns a part of the String. Syntax: public String substring(int startIndex) public String substring(int startIndex, int endIndex) Parameters: startIndex : starting index endIndex : ending index Returns: It returns a specified String. Throws: StringIndexOutOfBoundsException if start...

2 minutes read.

What is new in Java 17?

Java 17 LTS is the most recent long-term support release for the Java SE platform. Under the Oracle No-Fee Terms and Conditions License, which stands for long-term support, JDK 17...

6 minutes read.

BigDecimal toString() in Java

BigDecimal is a Java class that is a part of the java.math package and the java.base module. It implements the ComparableBigDecimal> interface and extends the Number class. The BigDecimal class...

3 minutes read.

Logger class in Java

Logging is a crucial component of Java that aids developers in tracking down mistakes. The logging technique is included with the computer language Java. The possibility of collect the log...

7 minutes read.

Java Output Formatting

Sometimes we want a program's output to be displayed in a specific format. The printf () function in the C programming language can be used to achieve this. We will...

4 minutes read.

Copy data/content from one file to another in java

In this article, you will be acknowledged about how to copy data or content from one file to another file. Also, you will be acknowledged about the classes and methods...

3 minutes read.

Java For Keyword

For as a keyword in java: When we need to run a set of statements repeatedly in Java, we use loops. The Java for loop offers a clear way to express...

4 minutes read.

Java.sql.Time Format

In JDBC API as a cover aroundjava.util.Date that handles SQL-specific requirements we use the java.sql.Time. The java.sql.Time extends java.util.Date class. To represent SQL TIME, without a date this class is...

6 minutes read.

Java Try-Catch Block

Java Try Block The handling of the exceptions in a block of code is done with the help of java try block. It throws the code that is enclosed in a...

3 minutes read.

Java Integer shortValue() method

The shortValue() method of Java Integer class returns a short value for this Integer after a narrowing primitive conversion. Syntax public short shortValue () Parameters NA Overrrides: The shortValue () overrides : shortValue in class Number  Return Value This...

1 minute read.

Java If Keyword

Definition: The if statement specifies a section of Java code that will run if an if statement's condition is false. The following conditional statements can be used in Java: To provide a block...

3 minutes read.

What’s New in Java 15

Sealed classes are the new concept that was introduced by Java 15. Sealed classes are a preview feature. Most of the features which are released in java 15 are in...

3 minutes read.

Different Ways to Take Input from User in Java

Any information provided to a system for use is known as user input. Any responsive software or application must include user input. In Java, there are 4 different ways to...

5 minutes read.

Java Sort String

In this article, you will be acknowledged about how to sort a string in Java. Introduction Firstly, let us revise what is string Strings are collections of characters that are frequently used in...

4 minutes read.

Reverse a String using Collections in Java

Generally, a String is a grouping of characters. Yet, in Java, a String is an item that addresses a succession of characters. The Java.lang.String class is utilized to make a...

5 minutes read.

Java Error Stack Trace

The stack trace in Java is an array of stacks.The stack trace reveals the console's location of an exception or error by gathering data from all program methods. The JVM...

3 minutes read.

PriorityQueue in Java

PriorityQueue in Java A PriorityQueue is a member of the Java Collection Framework and is used when the values are needed to be processed based on priority. Priority queue operates similar to...

8 minutes read.

Access specifiers in Java

What are access specifiers in Java? Access specifiers in Java are used to determine whether other classes can use a particular field or invoke a particular method. Access specifiers mainly specify...

7 minutes read.

Java FileOutputStream

What is FileOutputStream?When we need raw stream data written into a file, we need to look for another option: FileOutputStream. It is used when the file's data is byte-oriented. It comes under...

4 minutes read.

Java Math log10() Method

The log10() method of Math class returns the base 10 logarithmic value for the specified double argument. Syntax: public static double log10(double a) Parameters: The parameter ‘a’ represents a double value. Return Value: The log10() method...

2 minutes read.