Coding
Algorithms

Group Anagrams

Difficulty

Read the problem, hints and solution here. The editor needs a bigger screen: open this page on a laptop to write and run your code.

Available in Python and C++. You are solving it in Python. Switch to C++

Implement group_anagrams(words), which groups a sequence of lowercase words so that each group holds words that are anagrams of each other. It returns a sequence of groups, where each group is a sequence of words.

Two words are anagrams when one is a rearrangement of the other, so they use the same letters the same number of times. Order the groups by the first appearance of any of their members in the input, and keep the words inside a group in input order. A word that appears twice is two separate entries in the same group. The empty string is an anagram of itself. An empty input returns an empty result.

def group_anagrams(words: list[str]) -> list[list[str]]: ...

Examples

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

group_anagrams(["ab", "ba", "ab"])
# [["ab", "ba", "ab"]]  (the repeat is a second entry, not a merge)

Constraints

  • Up to \(2 \times 10^5\) words, each of length at most 12, over the letters a to z only.
  • Words may repeat, may be empty, and may be a single letter.
  • Comparing every word to every other word, or scanning every group so far for each new word, will not finish in time on the largest hidden test. Think about what one value computed per word would let you look a group up directly.
Rate this problem
Language:
Python 3.12C++23
group_anagrams
Rate this problem