|Group Anagrams
All Challenges

Group Anagrams

HardStrings

Given a list of strings words, group the anagrams together and return them as a list of lists.


Rules for the output:

- Each inner list must be sorted alphabetically

- The outer list must be sorted by the first element of each inner group


Words that are anagrams of each other contain the same characters in the same frequency.


This is used in content deduplication, thesaurus builders, and plagiarism detection systems.

Examples

Input: group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"])
Output: [["ate", "eat", "tea"], ["bat"], ["nat", "tan"]]
Three groups, each sorted
Input: group_anagrams(["a"])
Output: [["a"]]
Single word
Input: group_anagrams(["abc", "bca", "xyz"])
Output: [["abc", "bca"], ["xyz"]]
Two groups

Constraints

  • 1 <= len(words) <= 10,000
  • All words are lowercase letters only
  • Sort each inner group alphabetically
  • Sort outer list by the first element of each group
pythoneditor
Loading Python runtime…