← All Exercises

Group Anagrams

intermediatejavascript~20min

Background

Anagram grouping is a common interview problem that demonstrates hash-based classification and string canonicalization.

Problem

Write a function that takes an array of strings and groups anagrams together, returning an array of arrays.

Input

An array of strings containing lowercase letters only.

Output

An array of arrays, each containing strings that are anagrams of each other.

Sample tests

Sample 1

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

Your solution

Learning objective

Learn hash-based grouping using canonical keys and understand anagram properties.