Group Anagrams
Examples
Example 1:
Input: strs = ["act","pots","tops","cat","stop","hat"]
Output: [["hat"],["act", "cat"],["stop", "pots", "tops"]]
Example 2:
Input: strs = ["x"]
Output: [["x"]]
Example 3:
Input: strs = [""]
Output: [[""]]
Example 1:
Input: strs = ["act","pots","tops","cat","stop","hat"]
Output: [["hat"],["act", "cat"],["stop", "pots", "tops"]]
Example 2:
Input: strs = ["x"]
Output: [["x"]]
Example 3:
Input: strs = [""]
Output: [[""]]
Given an array of strings strs, group all anagrams together into sublists. You may return the output in any order.
An anagram is a string that contains the exact same characters as another string, but the order of the characters can be different.
1 <= strs.length <= 1000.0 <= strs[i].length <= 100strs[i] is made up of lowercase English letters.Use a hash map from a 26-length character count signature to the list of strings with that signature. For each string, build a count array for lowercase letters, convert it to a tuple key, and append the string to that group. This cleanly handles empty strings and repeated characters.
Two strings are anagrams if and only if their character frequency counts are identical. The count tuple is therefore a canonical signature for all anagrams, so grouping by that key places exactly the correct strings together.
O(n * k), where k is the max string lengthO(n * k) for stored output and keysclass Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
groups = defaultdict(list)
for s in strs:
counts = [0] * 26
for ch in s:
counts[ord(ch) - ord('a')] += 1
groups[tuple(counts)].append(s)
return list(groups.values())