Question
Leetcode link -> leetcode.com/problems/group-anagrams/descri..
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Explanation:
There is no string in strs that can be rearranged to form "bat".
The strings "nat" and "tan" are anagrams as they can be rearranged to form each other.
The strings "ate", "eat", and "tea" are anagrams as they can be rearranged to form each other.
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.
Approach
- loop through each word in the list
- loop through each char in the word
- Using the ASCII values of each character, count the occurrence
- Store this counter as a key and each word with the same occurrence of characters as a list value
- return the dict values as a list
Complexity
Time
๐( ๐ * k)
- n is the length of strs / number of words in the input str list
- k is the length of each word
Space
๐( n * k)
- m - the largest the result dict can grow is the length of strs input
- k - is the length of each word
Code
from collections import defaultdict
from typing import List
class Solution:
def group_anagram(self, strs:List[str]) -> List[List[str]]:
results = defaultdict(list)
for word in strs:
counter =[0] * 26
for char in word:
counter[ord(char) - ord("a")] += 1
results[tuple(counter)].append(word)
return list(results.values())
ย