String Anagram GroupsLoading saved progress…

String Anagram Groups

Implement stringAnagramGroups(words) — take an array of strings and bucket them so that strings which are anagrams of each other land in the same group. Two strings are anagrams when one is a rearrangement of the other's letters: "eat" and "tea" use the exact same letters the exact same number of times, just in a different order. The classic interview framing (LeetCode's "Group Anagrams") asks you to return the groups; here we pin down a deterministic output order so the result is testable.

Signature

// words: string[] — the input strings, in caller-supplied order.
// returns: string[][]
//   An array of groups. Each group is an array of the input strings
//   that are anagrams of one another. Ordering is deterministic — see Notes.
function stringAnagramGroups(words: string[]): string[][];

Examples

// Classic case: three anagram groups.
stringAnagramGroups(['eat', 'tea', 'tan', 'ate', 'nat', 'bat']);
// → [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
// Every word is unique — each ends up alone in its own singleton group.
stringAnagramGroups(['abc', 'xyz', 'foo']);
// → [['abc'], ['xyz'], ['foo']]

Notes

  • Anagram means same multiset of characters. "aab", "aba", and "baa" are all anagrams because each has two as and one b. A simple letter-set check is not enough — counts matter.
  • Output ordering is deterministic. Groups appear in the order their first member first appears in the input. Within a group, words stay in their original input order. This makes the result exactly comparable, not just "correct up to reordering."
  • Comparison is case-sensitive. "Tea" and "eat" are NOT anagrams here — 'T' and 't' are different characters. Treat the input as raw strings; do not lowercase.
  • Duplicates are kept. If the same word appears twice in the input, it appears twice in its group.
  • Empty input returns []. No words in, no groups out.
  • Don't worry about Unicode normalization, whitespace trimming, or grapheme clusters — assume plain strings compared character by character. Those extensions are covered in the solution's "Going further."
Loading editor…