add group-anagrams

This commit is contained in:
Sangeeth Sudheer 2022-04-21 14:16:42 +05:30
parent 1578bc52d6
commit 25fe22ae23
3 changed files with 64 additions and 0 deletions

View 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.

View 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())

View 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())