The Letter Kin

A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
medium
Seniority
L4

Problem

Given a list of strings, group strings that are anagrams. Return a list of groups. Within each group preserve the input order. The outer list order is the order each group's first element appears in the input.

Words that share the same letters belong together.

Example 1

Input:

words = ["eat","tea","tan","ate","nat","bat"]

Output:

[["eat","tea","ate"],["tan","nat"],["bat"]]

Example 2

Input:

words = [""]

Output:

[[""]]

Worked solution and explanation

Why this problem exists in real interviews

This tests anagram grouping using sorted character keys, a classic hash-based grouping problem. It probes whether a candidate can derive a canonical form for anagram comparison and use it as a dict key.


Break down the requirements

Step 1: Compute a canonical key for each word

Sort the characters: 'eat' and 'tea' both become 'aet'.

Step 2: Group words by their canonical key

Use a dict mapping sorted keys to lists of original words.

Step 3: Return the groups as a list of lists

Each group contains all words that are anagrams of each other.


The solution

Sorted-key anagram grouping
def group_anagrams(words: list) -> list:
    groups = {}
    for word in words:
        chars = sorted(word)
        key = ""
        for ch in chars:
            key += ch
        if key not in groups:
            groups[key] = []
        groups[key].append(word)
    result = []
    for group in groups.values():
        result.append(group)
    return result

Common follow-up questions