Group Anagrams

MediumArrays and hashing

You are given an array of lowercase words. Put the words that are anagrams of each other (the same letters, each the same number of times) into one group, and return the groups.

The groups can come back in any order, and so can the words inside each group.

Examples

Example 1
Input:  words = ["stop", "pots", "tops", "cat", "act", "dog"]
Output: [["stop", "pots", "tops"], ["cat", "act"], ["dog"]]

stop, pots and tops share their letters; so do cat and act. dog has no partner.

Example 2
Input:  words = ["solo"]
Output: [["solo"]]

One word makes one group.

Constraints

  • 1 ≤ words.length ≤ 10⁴
  • 0 ≤ words[i].length ≤ 100
  • Words use lowercase English letters only.

Stuck?

Hint 1

Two words are anagrams exactly when their letters, sorted, give the same string. Use that string as a key.

Hint 2

To skip the sort, count the 26 letters and join the counts into the key.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 8 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur