Group Anagrams
MediumArrays & Hashing · Cisco
Given a list of lowercase strings strs, group the strings that are anagrams of each other. Two strings are anagrams if one can be rearranged into the other, meaning they contain exactly the same letters with exactly the same counts (so "" is an anagram only of "").
Return a list of groups, where each group is a list of strings. Every input string must appear in exactly one group, and duplicates in the input stay duplicated in the output. The order of the groups, and the order of strings inside a group, do not matter.
Example 1
- Input:
- strs = ["listen","stone","silent","notes","enlist","cat"]
- Output:
- [["listen","silent","enlist"],["stone","notes"],["cat"]]
- Explanation
listen,silentandenlistall use e, i, l, n, s, t once each.stoneandnotesshare their letters too.catmatches nothing, so it is a group of one.
Example 2
- Input:
- strs = ["","b",""]
- Output:
- [["",""],["b"]]
- Explanation
- The two empty strings are anagrams of each other and stay together, both copies included.
Example 3
- Input:
- strs = ["abc","cab","abcc"]
- Output:
- [["abc","cab"],["abcc"]]
- Explanation
abcchas the same letters asabcbut a different count of c, so it is not an anagram of it.
Constraints
1 <= strs.length <= 10^40 <= strs[i].length <= 100strs[i]consists of lowercase English letters