Group Anagrams
Given an array of strings, group the anagrams together.
Return a list of groups, where each group is a list of the input strings that are anagrams of each other. Groups and the words inside them may be in any order.
For display, groups are printed one per line, words space-separated and sorted, groups sorted by first word.
Example
eat,tea,tan,ate,nat,bat
ate eat tea bat nat tan
- Input: six lowercase words,
eat,tea,tan,ate,nat,bat. Two words are anagrams exactly when they use the same letters the same number of times; the order of letters is irrelevant. - Count the letters of each word.
eat,teaandateall contain one , one and one , so they form one group.tanandnateach contain one , one and one , a second group.bathas one , one , one , a combination no other word shares, so it stands alone. - Every word lands in exactly one group, and the group sizes add up to the input length.
- Output: each group's words are shown in alphabetical order and the groups are ordered by their first word, giving three lines:
ate eat tea
bat
nat tan - Notice that
batandtanshare two letters but still land in different groups: one differing letter is enough to separate them. A word of length 0 would form its own group too.
Constraints
- 1 <= len(strs) <= 10^4
- 0 <= len(strs[i]) <= 100
- strs[i] is lowercase English letters