-
Notifications
You must be signed in to change notification settings - Fork 126
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
bb53e35
commit 39f1241
Showing
1 changed file
with
15 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |