Skip to content
Optimal Lab

Arrays & Hashing · 005Medium

Group Anagrams

Given an array of strings strs, group the anagrams together. Return the groups in any order; the strings inside a group may be in any order.

Constraints

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

Examples

groupAnagrams(["eat","tea","tan","ate","nat","bat"])
->  [["eat","tea","ate"], ["tan","nat"], ["bat"]]
groupAnagrams(["ab","ba","abc","cba","bac"])
->  [["ab","ba"], ["abc","cba","bac"]]   // groups and members may be in any order
groupAnagrams([""])            ->  [[""]]   // the empty string is its own group
groupAnagrams(["a"])           ->  [["a"]]   // single string
groupAnagrams(["abc", "def"])  ->  [["abc"], ["def"]]   // no anagrams at all
groupAnagrams(["", "", "a"])   ->  [["", ""], ["a"]]   // equal empty strings group together

Edge cases

  • The empty string is its own group.
  • Single-character strings.
Show the target complexity (spoiler)
Naive
O(n^2 * k) time — compare each string against every group.
Target
O(n * k) time — key each string by a 26-slot character count (or its sorted form) in a hash map.

Solve it

By hand, in your editor. The runner checks answers and timing.

git clone https://github.com/sarmadkung/optimal-round
cd optimal-round
# open problems/01-arrays-hashing/005-group-anagrams.js
./practice c 005

Stuck? Watch the pattern run