QuestionsDSA

Group Anagrams

Hash Map / SetMediumDSA

Group a list of strings so that anagrams are together. e.g. ['eat','tea','tan','ate','nat','bat'] → [['eat','tea','ate'],['tan','nat'],['bat']].

What it tests

Designing a good hash KEY. The insight: anagrams share a canonical form.

Approach & answer

The signature of a word is its sorted letters ('eat'→'aet'). Use that as a map key and push words into buckets. Sorting each word is O(k log k); a letter-count key (e.g. a 26-length tally serialized to 'a1e1t1') makes it O(k) if asked to optimize. The general move — 'group things equivalent under some transform' → derive a canonical key and bucket by it — is exactly how you'd dedupe records or cluster equivalent states. The Map's insertion order also gives you deterministic output grouping.

Use this technique when

'Group things that are equivalent under some transform' → derive a canonical key, bucket by it.

Complexity

Time O(n·k log k) · Space O(n·k)

References

js