Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Group anagrams

Group a list of words into anagram groups using hashing for efficient grouping.

Python practice15 minHashing & SetsIntermediateLast updated March 26, 2026

Problem statement

Given an array of strings, group the anagrams together. Two words are anagrams if they contain the same characters in any order. Return a list of groups (each group is a list of strings). To make outputs deterministic for testing, sort strings inside each group lexicographically and then sort the groups by their first element.

Task

Use hashing (dictionary) to group strings by their sorted character signature and return a deterministic ordering of groups and group members.

Examples

Basic grouping

Input

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

Output

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

eat, tea, and ate are anagrams -> sorted -> ['ate','eat','tea']; tan and nat -> ['nat','tan']; bat alone.

Input format

A list of strings, e.g. ['eat', 'tea', 'tan']

Output format

A list of lists of strings, with each inner list containing anagram group members (sorted), and groups sorted by their first member.

Constraints

0 <= len(strs) <= 10^4, 0 <= len(str) <= 100. All inputs are lowercase alphabetic strings.

Samples

Sample 1

Input

['a']

Output

[['a']]

Single word forms one group.