Menu
CoddyTech

Group Anagrams

You get a list of words strs. Two words are anagrams when one rearranges the other's letters, each used the same number of times. Group every word with all of its anagrams and return one string per group: its words in alphabetical order, joined by single spaces. Order the groups alphabetically by their first word.

A repeated word is listed twice in its group, and a word with no anagram forms a group of one. Alphabetical means dictionary order: aab comes before ab, and ab before abc.

Function

groupAnagrams(strs: string-array) → string-array
strsstring-array
the words to group, lowercase letters only
Returnsstring-array
one string per group: its words sorted and joined by spaces, groups ordered by their first word

Constraints

  • 1 ≤ strs.length ≤ 4000
  • 1 ≤ strs[i].length ≤ 8
  • Every word holds lowercase English letters only.

Examples

Input
strs = ["listen", "stone", "silent", "notes", "enlist", "onset", "tones", "apple"]
Output
["apple", "enlist listen silent", "notes onset stone tones"]
Explanation
enlist, listen and silent use e, i, l, n, s and t once each. notes, onset, stone and tones share e, n, o, s and t. apple matches nothing and, by first word, leads.
challenge icon

Follow-up

If the words could hold any Unicode characters, which key, sorted letters or letter counts, still works, and what would you change in it?

Reset code
def groupAnagrams(strs):
    # Write code here

Test #1

Test #2

Test #3

Argument

strs = ["listen", "stone", "silent", "notes", "enlist", "onset", "tones", "apple"]

Expected Output

["apple", "enlist listen silent", "notes onset stone tones"]