InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Arrays & Hashing

Group Anagrams

medium Original ↗ 00:00

Problem

Given a list of strings, gather them into groups where every string in a group is an anagram of the others — i.e. they use exactly the same multiset of letters, just in a different order. Return the groups as a list of lists; the order of groups and the order within a group don’t matter.

All strings consist of lowercase English letters.

Examples

Example 1: strs = ["eat","tea","tan","ate","nat","bat"][["eat","tea","ate"],["tan","nat"],["bat"]] “eat”, “tea”, “ate” all rearrange the letters {a,e,t}; “tan”/“nat” share {a,n,t}; “bat” is alone.

Example 2: strs = [""][[""]] A single empty string forms its own group.

Example 3: strs = ["a"][["a"]] One string, one group.

Constraints

  • 1 <= strs.length <= 10^4
  • 0 <= strs[i].length <= 100
  • Lowercase English letters only.

With up to 10^4 strings, comparing every pair (~10^8 string comparisons) is too slow — you need a per-string signature, not pairwise checks.

Think about it first

Hint 1 How would you check that just *two* strings are anagrams of each other, in one line?
Hint 2 If two strings are anagrams, some canonical transformation of them produces the *identical* result. What transformation? And where do you file things by identical key?
Hint 3 Map `sorted(word)` (as a tuple or joined string) to the list of words with that key — one dict pass groups everything. To shave the log factor, the key can instead be the 26-letter count vector as a tuple.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug