add group-anagrams
This commit is contained in:
parent
1578bc52d6
commit
25fe22ae23
27
0049_group-anagrams/README.md
Normal file
27
0049_group-anagrams/README.md
Normal file
@ -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.
|
13
0049_group-anagrams/python3/naive.py
Normal file
13
0049_group-anagrams/python3/naive.py
Normal file
@ -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())
|
24
0049_group-anagrams/python3/solution.py
Normal file
24
0049_group-anagrams/python3/solution.py
Normal file
@ -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())
|
Loading…
Reference in New Issue
Block a user