Skip to main content
CodeOath
← All problems

Problem

Group Anagrams

Medium
  • arrays
  • strings
  • hash-table

Two words are anagrams when the letters of one can be rearranged into the other. Split strs into groups: words that are anagrams of each other go in the same group, and words that are not go in different groups. Return the groups as an array of arrays.

The output order is fixed. Sort the words inside each group alphabetically, then sort the groups alphabetically by their first word.

Example 1
Input
strs = ["stop", "pots", "tops", "note", "tone", "west", "spot"]
Output
[["note", "tone"], ["pots", "spot", "stop", "tops"], ["west"]]
Explanation

stop, pots, tops and spot use the same letters, so do note and tone, and west has no partner. The words in each group are in alphabetical order, and so are the groups, by their first word: note, pots, west.

Example 2
Input
strs = ["", "b", ""]
Output
[["", ""], ["b"]]
Explanation

the empty string is a word too, and two empty strings are anagrams of each other, so they share a group. That group comes first because an empty string sorts before b.

Constraints:

  • 1 <= strs.length <= 10^4
  • each string uses lowercase English letters only, and may be empty

Tab indents. Press Esc, then Tab to leave the editor.

Run your code to see every test here. Nothing is submitted or recorded.