Print anagrams together in Python using List and Dictionary
Last Updated :
27 Jul, 2023
Given an array of words, print all anagrams together.
Examples:
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.
Implementation:
Python3
def allAnagram( input ):
dict = {}
for strVal in input :
key = ''.join( sorted (strVal))
if key in dict .keys():
dict [key].append(strVal)
else :
dict [key] = []
dict [key].append(strVal)
output = ""
for key,value in dict .items():
output = output + ' ' .join(value) + ' '
return output
if __name__ = = "__main__" :
input = [ 'cat' , 'dog' , 'tac' , 'god' , 'act' ]
print (allAnagram( input ))
|
Output
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)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...