Polski

Group anagrams

Words made of the same letters go into one group. An exercise in choosing a good map key – and in the order of results.

easy · typescript · javascript · python · csharp · java · go · 10 XP

A tag search wants to suggest "swapped letters" typos. The first step: group words into anagrams, i.e. words made of exactly the same letters with the same counts ("listen" and "silent").

Task

The function gets a list of words and returns a list of groups:

  • groups are ordered by the first occurrence of any of their words in the input,
  • inside a group words keep the input order, duplicates stay,
  • the empty string is a word too (all empty strings are anagrams of each other).

Signatures: groupAnagrams(words) (JS/TS), group_anagrams(words) (Python), Solution.GroupAnagrams (C#), Solution.groupAnagrams (Java), GroupAnagrams (Go).

Examples

InputResult
["eat", "tea", "tan", "ate", "nat", "bat"][["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]
["aab", "abb", "bab"][["aab"], ["abb", "bab"]]
["ad", "bc"][["ad"], ["bc"]]
[][]

Constraints

  • Up to 60,000 words, each 0–20 characters long, lowercase a–z only.

Expected complexity

O(n · k log k) time with a sorted-letters key or O(n · k) with a letter-count key (k – word length), O(n · k) memory.