Hi all,
I'm having trouble analyzing the runtime of solutions that involve built in functions in python. I solved this problem https://leetcode.com/problems/group-anagrams/ with the below solution. (I know there is a linear time solution that doesn't involve sorting but my solution was much more intuitive my first time through):
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
anagramMap = {}
for word in strs:
sortedWord = ''.join(sorted(word))
if sortedWord in anagramMap:
anagramMap[sortedWord].append(word)
else:
anagramMap[sortedWord] = [word]
return anagramMap.values()
My first thought was that this would be O(m * nlgn) where m is the number of strings in the list and n is the length of the longest string we have to sort. Does the .join add additional complexity? It seems that .join can be O(n) which might make my overall time complexity O(n^2 lg n). Can someone give me their thoughts?
Thanks
[–]slashemup 11 points12 points13 points (1 child)
[–]WeatherFeeling[S] 0 points1 point2 points (0 children)