☰ All problems

6. Group Anagrams

Given an array of strings strs, group the words that are anagrams of each other (same letters, any order). Return the groups in any order; the words inside a group can also be in any order.

Example 1
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Example 2
Input: strs = [""]
Output: [[""]]
Example 3
Input: strs = ["a"]
Output: [["a"]]

Constraints

  • 1 <= strs.length <= 10^4
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lowercase English letters
💡 Hint 1

Two words are anagrams exactly when their sorted letters are equal.

💡 Hint 2

Use that canonical form as a hash-map key. For O(k) keys, count the 26 letters instead of sorting.

/**
 * @param {string[]} strs
 * @return {string[][]}
 */
function groupAnagrams(strs) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc