Skip to main content

Group the words in a list that are anagrams of each other. For example, listen, silent, enlist, cat, act, dog becomes three groups: listen, silent and enlist; cat and act; and dog alone.

Coding rounds · Intermediate 1

Short answer

Give every word a key that all its anagrams share, and group words by that key in a dict. The simple key is the sorted letters: "".join(sorted(word)). For n words of average length m this is O(n times m log m) time and O(n times m) memory. A letter-count tuple removes the log factor.

Deeper answer

First clarify the input. Ask whether case matters, whether words can contain spaces or accents, and whether the same word can appear twice. Ask whether the order of groups or of words inside a group matters.

The idea is that two words are anagrams exactly when their sorted letters are equal. So build groups = defaultdict(list) and, for each word, run groups["".join(sorted(word))].append(word). At the end return list(groups.values()). Because a dict keeps insertion order, groups appear in the order their first word was seen.

Sorting each word costs O(m log m), so the total is O(n times m log m). For long words, use a count key instead: a tuple of 26 letter counts, which is O(m) per word. Test an empty list, single-letter words, a word with no anagram, and mixed case such as Listen and silent, where you call word.lower() before making the key. Say that comparing every pair of words would be O(n squared) and is the approach to avoid.

What a strong answer covers

Answer it out loud in the mock interview about 2.5 min

Follow-ups to expect

Common mistakes

Learn it

Lists and dictionaries

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.