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.
- Input
strs = ["stop", "pots", "tops", "note", "tone", "west", "spot"]- Output
[["note", "tone"], ["pots", "spot", "stop", "tops"], ["west"]]- Explanation
stop,pots,topsandspotuse the same letters, so donoteandtone, andwesthas no partner. The words in each group are in alphabetical order, and so are the groups, by their first word:note,pots,west.
- 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.