Group Anagrams
Medium · hash map
Given a list of lowercase words strs, group the words that are anagrams of each other and return the groups. Two words are anagrams when they use exactly the same letters the same number of times.
Inside each group, keep the words in the same order they have in strs, and keep repeated words (a word that appears twice in strs appears twice in its group). The groups themselves may be returned in any order. Every word belongs to exactly one group, and an empty string is an anagram of another empty string.
Examples
Example 1
Input: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
Output: [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]
"eat", "tea" and "ate" share the letters a, e, t. "tan" and "nat" share a, n, t. "bat" has no partner.
Example 2
Input: strs = [""]
Output: [[""]]
A single empty string forms one group.
Example 3
Input: strs = ["ab", "ba", "ab"]
Output: [["ab", "ba", "ab"]]
The repeated word stays in the group, in its original position.
Constraints
- 1 <= len(strs) <= 10^4
- 0 <= len(strs[i]) <= 100
- strs[i] contains only lowercase English letters.