Open In App

Find the word with most anagrams in a given sentence

Improve
Improve
Like Article
Like
Save
Share
Report

Given a string S in the form of a sentence, the task is to find the word from the text with the 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”

Method 1:

  • Initialise a map say unmap, to keep track of the frequency of each sorted word.
  • Initialise a variable maxx, this will keep track of the previous anagram count
  • Initialise a variable result for answer.
  • Iterate over each word of given string s
    • Keep the original word
    • Sort the word
    • Check if this sorted word exists in the map
      • If not exist then store unmap[word] = {current occurrence, original word}
      • Otherwise, increment the count of the frequency
    • Check if the anagram count is greater than the previous anagram count
      • Update the previous anagram count
      • Update the result
  • Return the result

Below is the implementation of the above approach:

C++




// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
string largestAnagramGrp(string s)
{
    // Initialise a map for keep track of frequency of
    // each sorted word.
    unordered_map<string, pair<int, string> > unmap;
 
    stringstream ss(s);
    string word;
 
    // Initialise a variable maxx, this will keep track of
    // previous anagram count
    int maxx = 0;
 
    // Initialise a variable result for answer.
    string result;
 
    // Iterate over each word of given string s
    while (ss >> word) {
 
        // Keep the original word
        string temp = word;
 
        // Sort the word
        sort(word.begin(), word.end());
 
        // Check if this sorted word exist in map
        if (unmap.count(word) == 0) {
 
            // If not exist then store unmap[word] =
            // {current occurrence, original word}
            unmap[word] = { 1, temp };
        }
        else {
 
            // Otherwise, increment the count of frequency
            unmap[word].first++;
        }
 
        // Check if the anagram count are greater than
        // previous anagram count
        if (unmap[word].first > maxx) {
 
            // Update the previous anagram count
            maxx = unmap[word].first;
 
            // Update the result
            result = unmap[word].second;
        }
    }
 
    // Return the result
    return result;
}
 
// Driver Code
 
int main()
{
    string S = "cat is not a dog and sword has no words "
               "when government creates act so what is tac";
    cout << largestAnagramGrp(S) << endl;
    return 0;
}
 
//This code is contributed by hkdass001


Java




import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
 
class Pair<K, V> {
 
    private K key;
    private V value;
 
    public Pair(K key, V value)
    {
        this.key = key;
        this.value = value;
    }
 
    public void setKey(K key) { this.key = key; }
 
    public void setValue(V value) { this.value = value; }
 
    public K getKey() { return key; }
 
    public V getValue() { return value; }
}
 
public class Gfg {
 
    public static String largestAnagramGrp(String s)
    {
        // Initialise a map for keep track of frequency of
        // each sorted word.
        Map<String, Pair<Integer, String> > unmap
            = new HashMap<>();
 
        StringTokenizer st = new StringTokenizer(s);
        String word;
 
        // Initialise a variable maxx, this will keep track
        // of previous anagram count
        int maxx = 0;
 
        // Initialise a variable result for answer.
        String result = "";
 
        // Iterate over each word of given string s
        while (st.hasMoreTokens()) {
 
            // Keep the original word
            String temp = st.nextToken();
 
            // Sort the word
            char[] wordArray = temp.toCharArray();
            Arrays.sort(wordArray);
            word = new String(wordArray);
 
            // Check if this sorted word exist in map
            if (!unmap.containsKey(word)) {
 
                // If not exist then store unmap[word] =
                // {current occurrence, original word}
                Pair<Integer, String> pair
                    = new Pair<>(1, temp);
                unmap.put(word, pair);
            }
            else {
 
                // Otherwise, increment the count of
                // frequency
                Pair<Integer, String> pair
                    = unmap.get(word);
                pair.setKey(pair.getKey() + 1);
            }
 
            // Check if the anagram count are greater than
            // previous anagram count
            if (unmap.get(word).getKey() > maxx) {
 
                // Update the previous anagram count
                maxx = unmap.get(word).getKey();
 
                // Update the result
                result = unmap.get(word).getValue();
            }
        }
 
        // Return the result
        return result;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String S
            = "cat is not a dog and sword has no words when government creates act so what is tac";
        System.out.println(largestAnagramGrp(S));
    }
}


Python3




# python Program to implement
# the above approach
def stringstream(s):
     
    res = []
    temp = []
    for i in range(len(s)):
         
        if s[i] != ' ':
            temp.append(s[i]);
        else:
            res.append(''.join(temp))
            temp.clear()
 
             
    res.append(''.join(temp))
    return res
 
 
def largestAnagramGrp(s):
 
    # Initialise a map for keep track of frequency of
    # each sorted word.
    unmap = {}
 
     
    ss = stringstream(s)
 
    # Initialise a variable maxx, this will keep track of
    # previous anagram count
    maxx = 0
 
    # Initialise a variable result for answer.
    result = []
    i = 0
     
    # Iterate over each word of given string s
    while (i < len(ss)):
 
        # Keep the original word
        word = ss[i]
        temp = ss[i]
 
        # Sort the word
        word = ''.join(sorted(word))
 
        # Check if this sorted word exist in map
        if word in unmap:
            # Otherwise, increment the count of frequency
            unmap[word][0] = unmap[word][0] + 1
        else:
            # If not exist then store unmap[word] =
            # {current occurrence, original word}
            unmap[word] = [1, temp]         
 
        # Check if the anagram count are greater than
        # previous anagram count
        if unmap[word][0] > maxx:
 
            # Update the previous anagram count
            maxx = unmap[word][0]
             
            # Update the result
            result = list(unmap[word][1])
        i = i + 1
     
    # Return the result
    return ''.join(result)
 
# Driver Code
S = "cat is not a dog and sword has no words when government creates act so what is tac"
print(largestAnagramGrp(S))
 
# This code is contributed by Nidhi goel.


C#




// C# Program to implement
// the above approach
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
 
class HelloWorld {
     
    public static string largestAnagramGrp(string s)
    {
        // Initialise a map for keep track of frequency of
        // each sorted word.
        Dictionary<string, KeyValuePair<int, string>> unmap = new Dictionary<string, KeyValuePair<int, string>>();
         
 
        var ss = s.Split(' ');
 
        // Initialise a variable maxx, this will keep track of
        // previous anagram count
        int maxx = 0;
 
        // Initialise a variable result for answer.
        string result = "";
 
        // Iterate over each word of given string s
        for(int i = 0;i < ss.Length; i++) {
 
            // Keep the original word
            string word = ss[i];
            string temp = ss[i];
 
            // Sort the word
            word = String.Concat(word.OrderBy(c => c));
 
            // Check if this sorted word exist in map
            if (unmap.ContainsKey(word) == false) {
 
                // If not exist then store unmap[word] =
                // {current occurrence, original word}
                unmap[word] = new KeyValuePair<int, string>(1, temp);
            }
            else {
 
                // Otherwise, increment the count of frequency
                unmap[word] = new KeyValuePair<int, string>(unmap[word].Key + 1, unmap[word].Value);
            }
 
            // Check if the anagram count are greater than
            // previous anagram count
            if (unmap[word].Key > maxx) {
 
                // Update the previous anagram count
                maxx = unmap[word].Key;
 
                // Update the result
                result = unmap[word].Value;
            }
        }
 
        // Return the result
        return result;
    }
     
    // Driver code.
    static void Main() {
        string S = "cat is not a dog and sword has no words when government creates act so what is tac";
        Console.WriteLine(largestAnagramGrp(S));
    }
}
 
// The code is contributed by Nidhi goel.


Javascript




// javascript Program to implement
// the above approach
function stringstream(s){
     
    let res = [];
    let temp = [];
    for(let i = 0; i < s.length; i++){
         
        if(s[i] != ' '){
            temp.push(s[i]);
        }
        else{
            res.push(temp.join(""));
            temp.splice(0, temp.length)
        }
    }
     
    res.push(temp.join(""));
    return res;
}
 
function largestAnagramGrp(s)
{
    // Initialise a map for keep track of frequency of
    // each sorted word.
    unmap = {};
 
     
    let ss = stringstream(s);
 
    // Initialise a variable maxx, this will keep track of
    // previous anagram count
    let maxx = 0;
 
    // Initialise a variable result for answer.
    let result = [];
    let i = 0
     
    // Iterate over each word of given string s
    while (i < ss.length) {
 
        // Keep the original word
        let word = ss[i];
        let temp = ss[i];
 
        // Sort the word
        word = word.split('').sort().join("");
 
        // Check if this sorted word exist in map
        if (word in unmap) {
            // Otherwise, increment the count of frequency
            unmap[word] = unmap[word] + 1;
        }
        else {
            // If not exist then store unmap[word] =
            // {current occurrence, original word}
            unmap[word] = [1, temp];           
        }
 
        // Check if the anagram count are greater than
        // previous anagram count
        if (unmap[word][0] > maxx) {
 
            // Update the previous anagram count
            maxx = unmap[word][0];
             
            // Update the result
            result = unmap[word][1].split('');
        }
        i = i + 1;
    }
     
    // Return the result
    return result.join("");
}
 
// Driver Code
let S = "cat is not a dog and sword has no words when government creates act so what is tac";
console.log(largestAnagramGrp(S));
 
// This code is contributed by Nidhi goel.


Output

cat

Time Complexity: O(n*log(n))
Auxiliary Space: O(n)

Approach: 

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: 

C++14




// C++ Program to find the word
// with most anagrams in a sentence
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the word with
// maximum number of anagrams
string largestAnagramGrp(vector<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
  unordered_map<long long, string> W;
 
  // Stores the frequencies
  // of products
  unordered_map<long long, long> P;
  for (string temp : arr)
  {
    long pdt = 1;
 
    // Calculate the product of
    // primes assigned
    for (char t : temp)
    {
      pdt *= prime[t - 'a'];
    }
 
    // If product already exists
    if (P.find(pdt) != P.end())
    {
      P[pdt]++;
    }
 
    // Otherwise
    else
    {
      W[pdt] = temp;
      P[pdt] = 1;
    }
  }
 
  // Fetch the most frequent product
  for (auto e : P)
  {
    if (max < e.second)
    {
      max = e.second;
      maxpdt = e.first;
    }
  }
 
  // Return a string
  // with that product
  return W[maxpdt];
}
 
// Driver Code
 
int main()
{
  char S[] = "please be silent and listen to what the professor says ";
  vector<string> arr;
 
  char *token = strtok(S, " ");
  while (token != NULL)
  {
    arr.push_back(token);
    token = strtok(NULL, " ");
  }
 
  cout << largestAnagramGrp(arr) << endl;
  return 0;
}
 
// This code is contributed by
// sanjeev2552


Java




// 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));
    }
}


Python3




# Python3 Program to find the word
# with most anagrams in a sentence
 
# Function to find the word with
# maximum number of anagrams
def largestAnagramGrp(arr):
     
    # Primes assigned to 26 alphabets
    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]
    max = -1
    maxpdt = -1
 
    # Stores the product and
    # word mappings
    W = {}
 
    # Stores the frequencies
    # of products
    P = {}
    for temp in arr:
        c = [i for i in temp]
        pdt = 1
 
        # Calculate the product of
        # primes assigned
        for t in c:
            pdt *= prime[ord(t) - ord('a')]
 
        # If product already exists
        if (pdt in P):
            P[pdt] = P.get(pdt, 0) + 1
 
        # Otherwise
        else:
            W[pdt] = temp
            P[pdt] = 1
 
    # Fetch the most frequent product
    for e in P:
        if (max < P[e]):
            max = P[e]
            maxpdt = e
 
    # Return a string
    # with that product
    return W[maxpdt]
 
# Driver Code
if __name__ == '__main__':
    S = "please be silent and listen to what the professor says"
    arr = S.split(" ")
    print(largestAnagramGrp(arr))
 
    # This code is contributed by mohit kumar 29


C#




// 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


Javascript




<script>
 
// JavaScript program to find the word
// with most anagrams in a sentence
// Function to find the word with
// maximum number of anagrams
function largestAnagramGrp(arr)
{
     
    // Primes assigned to 26 alphabets
    var 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, ];
     
    var max = -1;
    var maxpdt = -1;
     
    // Stores the product and
    // word mappings
    var W = {};
     
    // Stores the frequencies
    // of products
    var P = {};
     
    for (const temp of arr)
    {
        var c = temp.split("");
        var pdt = 1;
         
        // Calculate the product of
        // primes assigned
        for(const t of c)
        {
            pdt *= prime[t.charCodeAt(0) -
                       "a".charCodeAt(0)];
        }
         
        // If product already exists
        if (P.hasOwnProperty(pdt))
        {
            P[pdt] = P[pdt] + 1;
        }
         
        // Otherwise
        else
        {
            W[pdt] = temp;
            P[pdt] = 1;
        }
    }
     
    // Fetch the most frequent product
    for (const [key, value] of Object.entries(P))
    {
        if (max < value)
        {
            max = value;
            maxpdt = key;
        }
    }
     
    // Return a string
    // with that product
    return W[maxpdt];
}
 
// Driver Code
var S = "please be silent and listen" +
        " to what the professor says ";
var arr = S.split(" ");
 
document.write(largestAnagramGrp(arr));
 
// This code is contributed by rdtank
 
</script>


Output

silent

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



Last Updated : 09 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads