Find the word with most anagrams in a given sentence

Given a string S in the form of a sentence, the task is to find the word from the text with maximum number of its anagrams present in the given sentence.
Example: 
 

Input: S = “please be silent and listen to what the professor says” 
Output: silent 
Explanation: 
Only the word “silent” has an anagram(listen) present in the sentence. 
Input: S = “cat is not a dog and sword has no words when government creates act so what is tac” 
Output: cat 
Explanation: 
The word “cat” has two anagrams (“act”, “tac”) present in the sentence. 
The word “words” has an anagram (“sword”) present in the sentence. 
Hence, the word with the maximum anagrams is “cat”
 

 

Approach: 
Following observations need to be made to solve the program: 
 

Property of Prime Numbers: The product of any combination of prime numbers generates an unique number which cannot be obtained by any other combination of prime numbers. 
 



Follow the steps below to solve the problem: 
 

  • Assign each alphabet with a distinct prime number.
  • For each word in the given string, calculate the product of prime numbers assigned to the characters of that word and store it in a HashMap.
  • Calculate the product of prime numbers assigned to the characters of a word and store it in a HashMap.
  • Find the product with maximum frequency in the HashMap and print one of the corresponding anagrams as the answer.

Below is the implementation of the above approach:
 

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to find the word
// with most anagrams in a sentence
import java.util.*;
  
class GFG {
  
    // Function to find the word with
    // maximum number of anagrams
    private static String largestAnagramGrp(
        String arr[])
    {
        // Primes assigned to 26 alphabets
        int prime[]
            = { 2, 3, 5, 7, 11, 13, 17,
                19, 23, 29, 31, 37, 41,
                43, 47, 53, 59, 61, 67, 71,
                73, 79, 83, 89, 97, 101 };
  
        int max = -1;
        long maxpdt = -1;
  
        // Stores the product and
        // word mappings
        HashMap<Long, String> W
            = new HashMap<>();
  
        // Stores the frequencies
        // of products
        HashMap<Long, Integer> P
            = new HashMap<>();
  
        for (String temp : arr) {
            char c[] = temp.toCharArray();
            long pdt = 1;
  
            // Calculate the product of
            // primes assigned
            for (char t : c) {
                pdt *= prime[t - 'a'];
            }
  
            // If product already exists
            if (P.containsKey(pdt)) {
                P.put(pdt, P.get(pdt) + 1);
            }
  
            // Otherwise
            else {
                W.put(pdt, temp);
                P.put(pdt, 1);
            }
        }
  
        // Fetch the most frequent product
        for (Map.Entry<Long, Integer>
                 e : P.entrySet()) {
            if (max < e.getValue()) {
                max = e.getValue();
                maxpdt = e.getKey();
            }
        }
  
        // Return a string
        // with that product
        return W.get(maxpdt);
    }
  
    // Driver Code
    public static void main(String args[])
    {
        String S = "please be silent and listen"
                   + " to what the professor says ";
        String arr[] = S.split("[ ]+");
        System.out.println(largestAnagramGrp(arr));
    }
}

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find the word
// with most anagrams in a sentence
using System;
using System.Collections.Generic;
  
class GFG{
  
// Function to find the word with
// maximum number of anagrams
private static String largestAnagramGrp(String []arr)
{
      
    // Primes assigned to 26 alphabets
    int []prime = { 2, 3, 5, 7, 11, 13, 17,
                    19, 23, 29, 31, 37, 41,
                    43, 47, 53, 59, 61, 67, 71,
                    73, 79, 83, 89, 97, 101 };
  
    int max = -1;
    long maxpdt = -1;
  
    // Stores the product and
    // word mappings
    Dictionary<long
               String> W = new Dictionary<long,
                                          String>();
  
    // Stores the frequencies
    // of products
    Dictionary<long
               int> P = new Dictionary<long
                                       int>();
                                         
    foreach(String temp in arr) 
    {
        char []c = temp.ToCharArray();
        long pdt = 1;
  
        // Calculate the product of
        // primes assigned
        foreach(char t in c)
        {
            pdt *= prime[t - 'a'];
        }
  
        // If product already exists
        if (P.ContainsKey(pdt))
        {
            P[pdt] = P[pdt] + 1;
        }
  
        // Otherwise
        else 
        {
            W.Add(pdt, temp);
            P.Add(pdt, 1);
        }
    }
  
    // Fetch the most frequent product
    foreach(KeyValuePair<long, int> e in P)
    {
        if (max < e.Value)
        {
            max = e.Value;
            maxpdt = e.Key;
        }
    }
  
    // Return a string
    // with that product
    return W[maxpdt];
}
  
// Driver Code
public static void Main(String []args)
{
    String S = "please be silent and listen" +
               " to what the professor says ";
                 
    String []arr = S.Split(' ');
      
    Console.WriteLine(largestAnagramGrp(arr));
}
}
  
// This code is contributed by sapnasingh4991

chevron_right


Output: 

silent

 

Time Complexity: O(N), N is the length of the string excluding the blankspaces. 
Auxiliary Space: O(N) 
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : sapnasingh4991