InterviewPrepKit

Home / Coding / Arrays & Hashing

Group Anagrams

medium Original ↗
Solving tips
  • To group by an equivalence relation, design a canonical key that is identical iff two items are equivalent, then bucket with one hash-map pass instead of pairwise comparison.
  • Key each word by sorted(word) (O(k log k)) or, to drop the log factor, by a 26-length letter-count tuple (O(k)).
  • Keys must be hashable: use a tuple or joined string, not a list or Counter object.
  • Target O(n*k) time and space with the count-vector key; the empty string forms its own bucket naturally.

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.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.