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'
This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Python | Group Anagrams from given list
- Python | Pretty Print a dictionary with dictionary value
- Python - Convert Dictionary Value list to Dictionary List
- Python | Convert List of Dictionary to Tuple list
- Python - Extract Dictionary values list to List
- Python - Convert list to Single Dictionary Key Value list
- Python - Check List elements from Dictionary List
- Python - Convert Key-Value list Dictionary to List of Lists
- Given a sequence of words, print all anagrams together | Set 1
- Given a sequence of words, print all anagrams together using STL
- Given a sequence of words, print all anagrams together | Set 2
- How to use a List as a key of a Dictionary in Python 3?
- Python program to print the dictionary in table format
- Print all pairs of anagrams in a given array of strings
- Python - Keys associated with value list in dictionary
- Python - Remove Key from Dictionary List
- Python - Dictionary Key's Product in list
- Python - Key Value list pairings in Dictionary
- Difference between List and Dictionary in Python
- Python - Inner Nested Value List Mean in Dictionary
Improved By : nidhi_biet