Group Strings That Are Anagrams of Each Other

Implement groupAnagrams

Given an array of strings strs, group the anagrams together. Two strings are anagrams of each other if one can be rearranged into the other using every letter exactly once. You can return the groups — and the strings inside each group — in any order. Comparing every pair of strings directly is expensive. The key insight: two strings are anagrams exactly when their letters, sorted, produce the same string — so sorting each string's letters gives a canonical "key" that's identical for every member of a group. Scanning a list of seen keys works but is quadratic; storing groups in a hash map keyed by that sorted string collapses lookups to O(1), leaving sorting as the only real cost.

Example 1:

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

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

Example 2:

Input: strs = [""]

Output: [[""]]

Example 3:

Input: strs = ["a"]

Output: [["a"]]

+ 3 hidden test cases run on Submit.

Constraints:

  • 1 ≤ strs.length ≤ 10⁴
  • 0 ≤ strs[i].length ≤ 100
  • strs[i] consists of lowercase English letters

strs =

["eat", "tea", "tan", "ate", "nat", "bat"]