Group Anagrams
Group Anagrams
Given a list of n words, group all words that are anagrams of each other into the same group. Two words are anagrams if they contain the same characters with the same frequencies (order does not matter). Example: 6 words "eat tea tan ate nat bat" → groups: "ate eat tea" / "bat" / "nat tan"
Input format — only if your code reads from stdin
Input format: - First line: integer n (number of words) - Second line: n space-separated lowercase words Output: each group on its own line with words sorted alphabetically within the group. Print groups in lexicographic order of their first word.
Approach
Sort each word to produce its canonical "anagram key" (e.g., "eat" → "aet"). Use a hash map from sorted-key to the list of original words. Sort each group and the final group list before printing.
Input
Output
- •
1 ≤ n ≤ 10^4, words contain only lowercase English letters
More Hash Maps problems
Browse all coding problems →Press Run to test your custom input, or Submit to judge against all test cases.
Sign in to continue
Create a free account to run code, submit solutions and track progress.
- Free forever — no credit card
- 10+ languages with live execution
- Points, streaks & leaderboards