Open In App

Removing string that is an anagram of an earlier string

Given an array arr of strings, the task is to remove the strings that are an anagram of an earlier string, then print the remaining array in sorted order.

Examples: 

Input: arr[] = { “geeks”, “keegs”, “code”, “doce” }, N = 4 
Output: [“code”, “geeks”] 
Explanation: 
“geeks” and “keegs” are anagrams, so we remove “keegs”. 
Similarly, “code” and “doce” are anagrams, so we remove “doce”.

Input : arr[] = {“tea”, “ate”, “anagram”, “eat”, “gramaan”}, N = 5 
Output : [“anagram”, “tea”] 
Explanation: “ate” and “eat” are anagram of “tea”. 
“gramaan” is an anagram of “anagram” hence, array becomes [“anagram”, “tea”]. 
 

Approach: 

In order to check whether the given two strings are anagrams are not, we can simply sort both the strings and compare them. Also, to check if a string has occurred or not, we can use a HashSet

Follow the below steps to implement the idea:

Below is the implementation of the above approach.  





















Output
code geeks 

Time Complexity: O(N * (M log M)) where N is the size of the array and m is the length of the word.
Auxiliary space: O(N). 

Please suggest if someone has a better solution that is more efficient in terms of space and time.


Article Tags :