Group Words With the Same Letters

Medium · Arrays & Hashing · about 20 min

A word game stores each player's guess. Two guesses are in the same group when one is a rearrangement of the other's letters (same letters, same number of each). Group the guesses.

Return a list of strings: one string per group, with that group's words joined by a single space.

  • Inside a group, keep the words in their original order (repeats included).
  • Order the groups by where their first word appears in the input.
  • Every word has 1 to 20 lowercase letters. words has 0 to 10,000 words.

Example:

group_same_letters(["listen", "google", "silent", "enlist", "elgoog", "cat"]) → ["listen silent enlist", "google elgoog", "cat"]

Hints

  • What could you compute from a word that is the same for all its rearrangements, and different otherwise?
  • Sorting the letters of a word gives such a key.
  • A map from key to list of words keeps the groups; a map that remembers insertion order keeps the group order too.

Learn the pattern first: the Arrays & Hashing lesson.

More Arrays & Hashing problems