![]() |
VOOZH | about |
Given an array of words, print all anagrams together.
For example,
Input: array = {“cat”, “dog”, “tac”, “god”, “act”}
output: cat tac act, dog god
Explanation: cat tac and act are anagrams
and dog and god are anagrams as
they have the same set of characters.
Input: array = {“abc”, “def”, “ghi”}
output: abc, def, ghi
Explanation: There are no anagrams in the array.
Other approaches are discussed herein these posts:
This is a HashMap solution using C++ Standard Template Library which stores the Key-Value Pair. In the hashmap, the key will be the sorted set of characters and value will be the output string. Two anagrams will be similar when their characters are sorted. Now,
Implementation:
cat act tca abcd geeksforgeeks forgeeksgeeks geeksquiz zuiqkeegs
Note: Compile above program with -std=c++11 flag in g++
Complexity Analysis:
Another Approach: This program is designed to group anagrams from a given array of strings. The approach taken in this program is as follows:
Implementation:
cat act tca abcd geeksforgeeks forgeeksgeeks geeksquiz zuiqkeegs
Time Complexity: The time complexity of this code is O(n*m), where n is the number of strings in the given vector and m is the length of the longest string.
Auxiliary Space: The space complexity of this code is also O(n*m) because we are storing all the strings in the given vector in the store map.
This article is contributed by Mandeep Singh.