Group Anagrams / Similar Words Together

Problem Given a list of strings, group together the ones that are anagrams of each other (same multiset of characters, order irrelevant). The grouping rule may be generalised to any canonical-form equivalence, e.g. "same set of characters".

Input / Output

  • Input: an array of lowercase strings words.
  • Output: a list of groups, each group containing all strings that are mutual anagrams. Group order and within-group order are unconstrained.

Constraints

  • Up to 10^4 strings.
  • Each string up to ~100 characters, lowercase English letters.
  • Total input size fits comfortably in memory.

Example

  • Input: ['eat','tea','tan','ate','nat','bat']
  • Output: [['eat','tea','ate'],['tan','nat'],['bat']]
  • Tricky case: ['',''] groups both empty strings together; single-character strings each form their own group unless duplicated.
asked …
LeaderboardSalaryAccount