Editor

Group the Anagrams

#91 · Dictionaries and sets · Intermediate · 75 XP · about 12 min

Two words are anagrams when they use exactly the same letters the same number of times, like 'listen' and 'silent'. Write group_anagrams(words) that puts the words into groups of anagrams.

Return a list of groups. Sort the words inside each group alphabetically, then sort the groups by their first word. If a word appears more than once, keep every copy.

Examples

group_anagrams(['eat', 'tea', 'tan', 'ate', 'nat', 'bat'])
# returns [['ate', 'eat', 'tea'], ['bat'], ['nat', 'tan']]

group_anagrams(['listen', 'silent', 'enlist', 'google'])
# returns [['enlist', 'listen', 'silent'], ['google']]

group_anagrams([])
# returns []

In the first example 'bat' has no anagram in the list, so it forms a group on its own.

Constraints

  • 0 <= len(words) <= 10,000
  • Each word has 0 to 20 lowercase letters

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.