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.
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: S = “please be silent and listen to what the professor says”
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”
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”.
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:
Time Complexity: O(N), N is the length of the string excluding the blankspaces.
Auxiliary Space: O(N)