iq.lab
Python starts when a code cell comes near or you run one
mediumHash maps and sets target 25 min

Group anagrams

You get a list of lowercase words. Two words are anagrams when one is a rearrangement of the other: the same letters, each used the same number of times. Put the words into groups so that two words share a group exactly when they are anagrams, and return the groups as a list of lists.

Every word lands in exactly one group. A word with no anagram forms a group of one, and a word that appears twice appears twice in its group. A word can be empty, and all empty words are anagrams of each other. The groups can come in any order, and so can the words inside each group.

Example 1
Inputwords = ["rat", "tops", "art", "elf", "stop", "tar"]Output[["rat", "art", "tar"], ["tops", "stop"], ["elf"]]

rat, art and tar each use one a, one r and one t. elf has no anagram, so it is a group of one.

Example 2
Inputwords = ["ab", "abb", "bba"]Output[["ab"], ["abb", "bba"]]

abb and bba both have one a and two b's. ab has the same letters but different counts, so it stays apart.

Example 3
Inputwords = ["no", "on", "no"]Output[["no", "on", "no"]]

Both copies of no belong to the group.

Constraints
  • 1 ≤ len(words) ≤ 104

  • 0 ≤ len(word) ≤ 100 for each word

  • Words hold only lowercase English letters, a to z.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.