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:
- Create an auxiliary array to keep the resultant strings, and HashSet to keep a track of the string that we have found so far.
- Then iterate through the given string of array, sort the current string and check if the string is present in the HashSet.
- If the current string is not found in the HashSet, then push arr[i] in the resultant array, and insert the sorted string in the HashSet.
- Finally, sort the resultant array and print each string.
Below is the implementation of the above approach.
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.