Problem 13: Group Anagrams
Source: Dev.to
Overview
The task is to write a function that groups words that are anagrams of each other from a given list of strings.
An anagram is a word or phrase formed by rearranging the letters of another word or phrase, using all original letters exactly once.
Example
group_anagrams(['listen', 'silent', 'hello', 'world', 'enlist'])
Expected output
[['listen', 'silent', 'enlist'], ['hello'], ['world']]
Solution
Python implementation
def group_anagrams(words):
"""
Groups words that are anagrams of each other.
"""
# Edge case: None or empty input
if not words:
return []
anagram_groups = {}
for word in words:
# Create a case‑insensitive, sorted tuple as the dictionary key
key = tuple(sorted(word.lower()))
if key in anagram_groups:
anagram_groups[key].append(word)
else:
anagram_groups[key] = [word]
return list(anagram_groups.values())
Test
print(group_anagrams(['listen', 'silent', 'hello', 'world', 'enlist']))
# Output: [['listen', 'silent', 'enlist'], ['hello'], ['world']]
Explanation
- Handle edge cases – If
wordsisNoneor empty, return an empty list. - Create a signature for each word
- Convert the word to lowercase (
word.lower()) to make the grouping case‑insensitive. - Sort its characters (
sorted(...)). - Convert the sorted list to a tuple so it can be used as a dictionary key.
- Convert the word to lowercase (
- Group words – Use a dictionary (
anagram_groups) where each key is the signature tuple and the value is a list of words sharing that signature. - Return the groups – Convert the dictionary’s values view to a list and return it.
Walkthrough with ['listen', 'silent', 'hello']
| Step | Word | Key (sorted tuple) | Action |
|---|---|---|---|
| 1 | listen | ('e', 'i', 'l', 'n', 's', 't') | New entry → {'...': ['listen']} |
| 2 | silent | ('e', 'i', 'l', 'n', 's', 't') | Key exists → append → {'...': ['listen', 'silent']} |
| 3 | hello | ('e', 'h', 'l', 'l', 'o') | New entry → {'...': ['hello']} |
Result: [['listen', 'silent'], ['hello']]
Happy coding! 💻