From 25fe22ae23f9d08b64f15540da2a1690f1727ab4 Mon Sep 17 00:00:00 2001 From: Sangeeth Sudheer Date: Thu, 21 Apr 2022 14:16:42 +0530 Subject: [PATCH] add group-anagrams --- 0049_group-anagrams/README.md | 27 +++++++++++++++++++++++++ 0049_group-anagrams/python3/naive.py | 13 ++++++++++++ 0049_group-anagrams/python3/solution.py | 24 ++++++++++++++++++++++ 3 files changed, 64 insertions(+) create mode 100644 0049_group-anagrams/README.md create mode 100644 0049_group-anagrams/python3/naive.py create mode 100644 0049_group-anagrams/python3/solution.py diff --git a/0049_group-anagrams/README.md b/0049_group-anagrams/README.md new file mode 100644 index 0000000..75088df --- /dev/null +++ b/0049_group-anagrams/README.md @@ -0,0 +1,27 @@ +Given an array of strings `strs`, group **the anagrams** together. You can return the answer in **any order**. + +An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. + +**Example 1:** + + Input: strs = ["eat","tea","tan","ate","nat","bat"] + Output: [["bat"],["nat","tan"],["ate","eat","tea"]] + + +**Example 2:** + + Input: strs = [""] + Output: [[""]] + + +**Example 3:** + + Input: strs = ["a"] + Output: [["a"]] + + +**Constraints:** + +* `1 <= strs.length <= 104` +* `0 <= strs[i].length <= 100` +* `strs[i]` consists of lowercase English letters. \ No newline at end of file diff --git a/0049_group-anagrams/python3/naive.py b/0049_group-anagrams/python3/naive.py new file mode 100644 index 0000000..c05bf38 --- /dev/null +++ b/0049_group-anagrams/python3/naive.py @@ -0,0 +1,13 @@ +# Time: O(N * MlogM) where N is len(strs) and M is num of chars in a string +# Space: O(N) + +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + groups = {} + + for s in strs: + s_sorted = ''.join(sorted(s)) + + groups[s_sorted] = groups.get(s_sorted, []) + [s] + + return list(groups.values()) diff --git a/0049_group-anagrams/python3/solution.py b/0049_group-anagrams/python3/solution.py new file mode 100644 index 0000000..459b7d4 --- /dev/null +++ b/0049_group-anagrams/python3/solution.py @@ -0,0 +1,24 @@ +# Time: O(N ยท M) +# Space: O(N) + +from collections import Counter, defaultdict + +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + # If key doesn't exist, creates empty list using `list` + # factory/ctor function + groups = defaultdict(list) + + for s in strs: + # Keep counter for num of times each letter appeared + counts = [0] * 26 + + for c in s: + i = ord(c) - ord('a') + counts[i] += 1 + + # Lists aren't hashable, so we need to convert the counts + # to tuple so that we can key them + groups[tuple(counts)].append(s) + + return list(groups.values())