Group anagrams

strings

Group anagrams

Pinterest Python Interview Question

Pinterest's search team groups search terms that are made of the same letters, so it can spot typos and word games.

Write a function group_anagrams(words) that groups words that are anagrams of each other. Return a list of groups. Sort the words inside each group alphabetically, and sort the groups by their first word.

Asked of

  • Data Analyst
  • Data Engineer
  • Data Scientist
  • ML Engineer
  • AI Engineer

Example 1

Input

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

Output

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

Example 2

Input

words = ["a"]

Output

[["a"]]

Explanation

In the first example, "eat", "tea" and "ate" use the same letters, as do "tan" and "nat", while "bat" stands alone. Sorted inside and then by first word, the groups are ["ate", "eat", "tea"], ["bat"] and ["nat", "tan"].

Submit also runs 3 hidden test cases that check edge cases.