Skip to content

Commit

Permalink
solved group anagram
Browse files Browse the repository at this point in the history
  • Loading branch information
SamTheKorean committed May 20, 2024
1 parent bb53e35 commit 39f1241
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions group-anagrams/samthekorean.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# TC : O(nwlog(w))
# reason : n being the number of words and w being the length of each word, therefore the total time complexity is n times wlog(w) (time complexity for sorting each word)
# SC : O(w*n)
from collections import defaultdict


class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
anagrams = defaultdict(list)

# Use sorted word as a string and append it with the original word so the word containing same charactors with the same number of existence can be in the same group
for word in strs:
anagrams[str(sorted(word))].append(word)

return anagrams.values()

0 comments on commit 39f1241

Please sign in to comment.