49. Group Anagrams#
Difficulty: Medium
Link to Problem: To see the Group Anagrams problem on LeetCode, click here!
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.
Constraints:
1 <= `strs.length <= \(10^4\)
0 <= strs[i].length <= 100
strs[i]
consists of lowercase English letters.
Solution:#
Here’s a Python function to solve this problem:
from collections import defaultdict
def groupAnagrams(strs):
ans = defaultdict(list)
# Iterate through the list of input strings
for s in strs:
# Initialize a list to represent character counts for each character (a-z)
count = [0] * 26
# Count the occurrences of each character in the current word
for c in s:
count[ord(c) - ord("a")] += 1
# Use a tuple of character counts as the key and append the word to the anagram group
ans[tuple(count)].append(s)
# Convert the values (lists of anagrams) to a list of lists
return list(ans.values())
Explanation:#
Inside the method, a
defaultdict
calledans
is created to store anagram groups. This dictionary will have a list as its default value, meaning that each key in the dictionary will be associated with an empty list by default.The code then iterates through the list of input strings,
strs
, using afor
loop. For each words
instrs
, it performs the following steps:It initializes a list
count
of length 26, where each element represents the count of a specific character (a-z) in the words
.The code then iterates through the characters of
s
. For each characterc
, it increments the corresponding count in thecount
list based on its ASCII value.After counting the characters in
s
, it converts thecount
list into a tupletuple(count)
to use as a key for theans
dictionary.It appends the word
s
to the list associated with the key (tuple) in theans
dictionary. This groups all anagrams of the same word together under the same key.
After processing all words in
strs
, the code converts the values of theans
dictionary (which are lists of anagrams) to a list of lists using thelist()
constructor.Finally, the code returns the list of anagram groups, which is the result of grouping the anagrams in the input list.
In summary, the code efficiently groups anagrams together by counting the characters in each word and using a dictionary to store them under the same key. The result is a list of lists, where each inner list represents a group of anagrams.
Test cases#
# Example 1: Group anagrams from a list of words
strs1 = ["eat", "tea", "tan", "ate", "nat", "bat"]
result1 = groupAnagrams(strs1)
print(result1)
[['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
# Example 2: Group anagrams from a list with an empty string
strs2 = [""]
result2 = groupAnagrams(strs2)
print(result2)
[['']]
# Example 3: Group anagrams from a list with a single word
strs3 = ["a"]
result3 = groupAnagrams(strs3)
print(result3)
[['a']]
Time and Space Complexity Analysis#
Let’s analyze the time and space complexity of the groupAnagrams
method:
Time Complexity:
First, we create an instance of the
Solution
class, which is an O(1) operation.Inside the
groupAnagrams
method, we iterate through the list of input stringsstrs
once in a loop:For each word in
strs
, we perform character counting, which is done in O(K) time, where K is the maximum length of a word in the list.
The overall time complexity of the method is O(N * K), where N is the number of words in the input list
strs
, and K is the maximum length of a word instrs
.
Space Complexity:
We use a
defaultdict
calledans
to store the anagram groups. In the worst case, each word belongs to a distinct anagram group, so the space complexity forans
is O(N).Within the loop, we create a
count
list of length 26 to store character counts for each word. This is a fixed-size list and does not depend on the input size, so it has a constant space complexity of O(26), which is effectively O(1).The space used for other variables is also constant and does not depend on the input size.
The final result,
result
, is a list of lists that contains the grouped anagrams. In the worst case, each word is a distinct anagram group, so the space complexity forresult
is O(N).The overall space complexity of the method is O(N) due to the space used by
ans
andresult
. The space used by thecount
list and other variables is constant and does not significantly affect the overall space complexity.
In summary, the time complexity of the groupAnagrams
method is O(N * K), and the space complexity is O(N), where N is the number of words in the input list strs
, and K is the maximum length of a word in strs
.
Challenging Exercises:#
Anagramic Palindromes: Given a list of strings, find all the groups of anagrams where each group contains words that can be rearranged into a palindrome. For example, in the list [“bat”, “tab”, “act”, “tac”, “dog”], there are two groups: [“bat”, “tab”, “act”, “tac”] and [“dog”].
Largest Anagram Group: Given a list of strings, find the largest group of anagrams. Return the list of anagrams in that group. If there are multiple largest groups, return all of them.