Skip to main content

Group Anagrams

MediumStringsHash mapSorting163 tests

Given an array of strings strs, group the anagrams together.

An anagram is a word formed by rearranging the letters of another, using every letter exactly once.

Return a list of groups. Sort the strings inside each group alphabetically; the groups themselves may appear in any order.

Example 1

text

The groups may come back in any order — only the contents matter.

Example 2

text

Example 3

text

The whole problem is choosing a key that two anagrams share and nothing else does.

Examples

Example 1

Input:
["eat","tea","tan","ate","nat","bat"]
Output:
[["ate","eat","tea"],["nat","tan"],["bat"]]

"eat", "tea" and "ate" share the letters a/e/t. Each group is sorted alphabetically; the groups may come in any order.

Example 2

Input:
[""]
Output:
[[""]]

One empty string forms one group.

Example 3

Input:
["a"]
Output:
[["a"]]

A single word is its own group.

Constraints

  • 1 <= strs.length <= 10^4
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lowercase English letters.
  • Each group must be sorted alphabetically; group order does not matter.

Run checks your code against the 3 examples. Submit checks it against all 163 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.