Menu
CoddyTech

Group Anagrams

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

A word that appears twice 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 each use e, i, l, n, s and t once. notes, onset, stone and tones share e, n, o, s and t, and apple matches nothing. By first word the groups run apple, enlist, notes.

lock icon+15 hidden tests on Submit

challenge icon

Follow-up

Suppose the words could hold any Unicode characters instead of 26 lowercase letters. Which of the two keys, sorted letters or letter counts, still works, and what would you change in it?

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

Case 1

Case 2

Case 3

Input

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

Expected

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