Beyond Big O

Anagram groups

Anagram groups

Medium

Solution guide

Reveal solution guide — spoilers

Approach

  1. For each word, count its 26 lowercase ASCII letters. Use the complete count vector as a key: a tuple in Python, a fixed-size array in Go, or an unambiguous encoding.
  2. Map each signature to the index of its group in a separate output list. Create a group only the first time that signature appears.
  3. Append each original word to its group as it is encountered. This preserves duplicates and word order without relying on unordered map iteration.

Why it works

Two words are anagrams exactly when each letter has the same frequency, so equal signatures identify precisely the intended groups. Creating groups on first encounter orders them by their first input member, and appending during the same scan preserves order within each group.

Complexity

O(C + W) time for C total characters and W words with the fixed 26-letter alphabet. Auxiliary signature/index storage is O(G), counting fixed-size signatures, for G groups; returned group lists hold O(W) word references.

Edge cases to check

  • Empty words share the all-zero signature and form a group.
  • Repeated identical words remain repeated output members; an empty input produces no groups.
  • Naively concatenating decimal counts without separators can collide; use a full tuple/array or an unambiguous encoding.
Editor options
Typing preferences

Saved in this browser.

Restoring local drafts…