Print anagrams together in Python using List and Dictionary
Given an array of words, print all anagrams together.
Input: arr = [‘cat’, ‘dog’, ‘tac’, ‘god’, ‘act’]
Output: ‘cat tac act dog god’
This problem has existing solution please refer Anagrams and Given a sequence of words, print all anagrams together links. We will solve this problem in python using List and Dictionary data structures. Approach is very simple :
- Traverse list of strings.
- Sort each string in ascending order and consider this sorted value as Key and original value as Value of corresponding key. Check if key is not present in dictionary that means it is occurring first time, so map a empty list to Key and append value in it, if key is already present then simple append the value.
- Now each key will contain list of strings which are anagram together.
cat tac act dog god
Time Complexity: O(n), where n is the total number of the characters in the given input.
Auxiliary Space: O(n)
This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Login to comment...