☰ All problems

Group Anagrams

A word-puzzle app wants to show players which words can be spelled from the same set of letter tiles. Two words share a set of tiles when they are anagrams: the same letters, each used the same number of times, possibly in a different order.

Given an array of lowercase words strs, sort the words into such groups and return the list of groups. Every word belongs to exactly one group, so all copies of a repeated word end up together. Words may be empty, and all empty words share one group. The groups can be returned in any order, and so can the words inside each group.

Example 1
Input: strs = ["race","care","acre","bat","tab","sun"]
Output: [["race","care","acre"],["bat","tab"],["sun"]]

Explanation: race, care and acre each use one a, c, e and r. sun has no partner, so it forms a group of one.

Example 2
Input: strs = ["loop","pool","polo","lop"]
Output: [["loop","pool","polo"],["lop"]]

Explanation: lop has only one o, so it is not an anagram of the other three.

Example 3
Input: strs = ["x","","x"]
Output: [["x","x"],[""]]

Explanation: Both copies of x land in the same group, and the empty word gets a group of its own.

Constraints

  • strs contains between 1 and 10^4 words.
  • Each word is 0 to 100 characters long and uses only 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