InternDoor

Group the anagrams

Mediumstrings · hashing · sorting

Reported in interviews at (where)

words is a list of lowercase words. Two words are anagrams when one is the other with its letters rearranged, like "listen" and "silent". Put the words into groups of anagrams: every word goes into exactly one group, a word with no anagram gets a group of its own, and a repeated word keeps every copy, all in the same group.

So that there is one right answer, sort the words inside each group alphabetically, and order the groups by their first word.

Example 1
Input
words = ["stop","pots","meal","tops","male","x"]
Output
[["male","meal"],["pots","stop","tops"],["x"]]

"stop", "pots" and "tops" share the letters o, p, s, t; "meal" and "male" share a, e, l, m; "x" has no partner. The groups are ordered by their first words: male, pots, x.

Example 2
Input
words = ["ab","ba","ab"]
Output
[["ab","ab","ba"]]

Both copies of "ab" stay, in the same group as "ba".

Example 3
Input
words = ["night"]
Output
[["night"]]

One word makes one group.

Limits

  • 1 <= words.length <= 10000
  • 1 <= words[i].length <= 20
  • words[i] holds lowercase English letters

Hints

Hint 1

Two words are anagrams exactly when their letters, sorted, are the same. Use that sorted form as a key.

Hint 2

A map from key to the list of words with that key does the grouping in one pass. Sort each list, then sort the lists.

Where this was reported

Our own problem on the task these candidates describe; the wording, examples and tests are InternDoor’s.

Run your code to check it on the examples. Submit runs every hidden test.

Ready for the real one?

Engineering internships and entry-level jobs in India, newest first.