Winner Of An Election Geeks For Geeks

 class Solution

{

    //Function to return the name of candidate that received maximum votes.

    public static String[] winner(String arr[], int n)

    {

        TreeMap<String,Integer> map=new TreeMap<String,Integer>();

        for(int i=0;i<arr.length;i++){

            if(map.containsKey(arr[i])){

                map.put(arr[i],map.get(arr[i])+1);

            }

            else

                map.put(arr[i],1);

        }

PriorityQueue<Integer> pq=new PriorityQueue<Integer>();

int a=0;

for (Map.Entry<String, Integer> entry : map.entrySet()) {

a=entry.getValue();

if(pq.isEmpty()){

pq.add(a);

}

else{

if(pq.peek()<a){

pq.remove();

pq.add(a);

}

}

}

String arr2[]=new String[2];

for (Map.Entry<String, Integer> entry1 : map.entrySet()) {

int a1=entry1.getValue();

if(a1==pq.peek()){

arr2[0]=entry1.getKey();

arr2[1]=String.valueOf(a1);

break;

}

}


return arr2;

        

    }

}


Approach:

Here we will add the string and their frequencies in the treemap. (TreeMap is used here as it is sorted and will keep track of first coming entries with the highest frequencies.)

Then we will use one priority queue of size 1. We will traverse the tree set with the help of a map. entry and will see all the values. If the existing value in the queue is less than the next incoming value from the entry set we will change the remove the value from the queue and add the new greater value. As a result in the last, we will be having a maximum value in the queue.

In the end, we will have the max value and we will store that key and (string typecasting)value in the array and return it.

TIME:O(N)[GFG TIME : 0.9/2.3]
SPACE:O(N)


Thanks for Reading😇.

Comments

Popular posts from this blog

Solutions Of Practice Questions Dated 01-06-2022

CODEFORCES SPY DETECTED ROUND 713

Maximum Winning Score Geeks For Geeks