From 39f1241ded793beaccea394ed28321bb04aeb36d Mon Sep 17 00:00:00 2001 From: Sam2022moon <104721736+Sam2022moon@users.noreply.github.com> Date: Mon, 20 May 2024 15:49:38 +0900 Subject: [PATCH] solved group anagram --- group-anagrams/samthekorean.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 group-anagrams/samthekorean.py diff --git a/group-anagrams/samthekorean.py b/group-anagrams/samthekorean.py new file mode 100644 index 000000000..4ea2fcf08 --- /dev/null +++ b/group-anagrams/samthekorean.py @@ -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()