This is not a homework problem. I'm prepping for an interview, and have done quite a bit of research on links on this post. I coded up a solution based on a suggestion, but I disagree with the time complexity proposed. I'd like to know whether I'm incorrect/correct in my assertion.
Below is a function to spit out group of anagrams. It sorted each input words and put the sorted input word in a dictionary. I wrote the code myself based on a hint from geeksforgeeks posting that suggest:
Using sorting: We can sort array of strings so that all anagrams come together. Then print all anagrams by linearly traversing the sorted array. The time complexity of this solution is O(mnLogn) (We would be doing O(nLogn) comparisons in sorting and a comparison would take O(m) time). Where n is number of strings and m is maximum length of a string.
I disagree with the time complexity mentioned
I think the time complexity for the following code is n(m log m). Space complexity is: O(2n)= O(n) for the results and sorted_dict variable
n= number of words, m = number of character in a word
def groupAnagrams(strs):
sorted_dict ={}
results=[]
for each in strs:#loop: O(n)
#time complexity for sort: O(m log m).
sorted_str = "".join(sorted(each.lower())) #O(m)
if not sorted_dict.get(sorted_str): #0(1)
sorted_dict[sorted_str] = []
sorted_dict[sorted_str].append(each) #0(1)
for k,v in sorted_dict.items(): #0(n)
results.append(v)
return results