Most Frequent Word in Array

Most Frequent Word in Array

Given an array arr containing N words consisting of lowercase characters. Your task is to find the most frequent word in the array. If multiple words have same frequency, then print the word whose first occurence occurs last in the array as compared to the other strings with same frequency.

Input Format

Input consist of two lines. The first line contains a number N representing the size of the array. Next line consists of N words separated by space.

Output Format

Print a single word which is the most frequent word in the array.

Example 1

Input

3
geeks for geeks

Output

geeks

Explanation

“geeks” comes 2 times.

Example 2

Input:

2
hello world

Output:

world

Explanation

“hello” and “world” both have 1 frequency. We print “world” as its first occurrence comes last in the input array.

Constraints

1 <= N <= 50000

1 <= |each string| <= 50

Note: Sum of length of all strings does not exceed 5*10^5

Solution:–

import java.util.*;
import java.lang.*;
import java.io.*;

public class Main
{
	public static void main (String[] args) throws java.lang.Exception
	{
		//your code here
                Scanner sc = new Scanner(System.in);
      int n = sc.nextInt();
             String []arr = new String[n];
        for(int i =0;i<n;i++){
            arr[i]=sc.next();
        }

       HashMap<String,Integer> hm = new HashMap<>();
        HashMap<String,Integer> hm1 = new HashMap<>();
        for(int i=0;i<n;i++){
            if(hm.containsKey(arr[i])){
                hm.put(arr[i] , hm.get(arr[i])+1);
            }
            else{
                hm.put(arr[i],1);
            }
        }
       
        int max=0;
         for(String i : hm.keySet()){
            max = Math.max(hm.get(i), max);
        }
        
          for(int i = 0; i<n; i++){
            if(hm.get(arr[i]) == max && !hm1.containsKey(arr[i])){
                hm1.put(arr[i], i);
            }
        }
       
        String ans="";
        max=0;
         for(String i : hm1.keySet()){
            max = Math.max(hm1.get(i), max);
        }
      
       for(String i : hm1.keySet()){
           if(hm1.get(i)==max){
               ans=i;
           }
            
        }
    
       System.out.print(ans) ;

	}
}

Add a Comment

Your email address will not be published. Required fields are marked *