All coding questions

Group Anagrams

medium
Blind 75NeetCode 150stringshashing

Problem

Given a list of strings, cluster them so that words which are anagrams of each other land in the same group. Return the list of groups in any order.

Examples

Input: words = ["eat", "tea", "tan", "ate", "nat", "bat"]
Output: [["eat","tea","ate"],["tan","nat"],["bat"]]
Words sharing the same letter multiset are grouped together.

Constraints

  • 1 <= words.length <= 10^4
  • 0 <= words[i].length <= 100
  • Words consist of lowercase English letters
Hints(tap to reveal)
  • 1. Anagrams share a canonical form.
  • 2. Sorting each word, or a 26-letter count signature, makes a stable key.
Optimal approach(spoiler)
  1. Use a hash map keyed by a canonical signature of each word.
  2. Derive the signature by sorting the word or by a fixed-length character count.
  3. Append each word to the bucket for its signature.
  4. Return all the bucket values.
  5. O(n * k log k) with sorting, or O(n * k) with count keys.

Ready to solve it?

Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.

Practice in the editor