Problem 13: Group Anagrams

Published: (February 9, 2026 at 09:53 PM EST)
2 min read
Source: Dev.to

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

  1. Handle edge cases – If words is None or empty, return an empty list.
  2. 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.
  3. 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.
  4. Return the groups – Convert the dictionary’s values view to a list and return it.

Walkthrough with ['listen', 'silent', 'hello']

StepWordKey (sorted tuple)Action
1listen('e', 'i', 'l', 'n', 's', 't')New entry → {'...': ['listen']}
2silent('e', 'i', 'l', 'n', 's', 't')Key exists → append → {'...': ['listen', 'silent']}
3hello('e', 'h', 'l', 'l', 'o')New entry → {'...': ['hello']}

Result: [['listen', 'silent'], ['hello']]

Happy coding! 💻

0 views
Back to Blog

Related posts

Read more »