Group the twins
medium
New here? How this page works
- Read the Problem tab. Read it twice. Look at the examples: what goes in, what should come out.
- Open Break it down. Answer the questions in your own words. This is your plan.
- Write code on the right. Start small. Stuck on a blank page? Press “Write my plan as comments”.
- Press Run examples. See which examples pass. Red ones show what your code gave and what was expected.
- Stuck? Use Hints, one at a time. Still stuck after all of them? Read the Walkthrough. That's learning, not cheating.
- Press Submit. It runs hidden tests too. Pass them all, and it's solved.
Two words are letter twins if one can be made by rearranging all the letters of the other, like tea and eat.
Given a list of words, put them into groups so that every word in a group is a letter twin of the others, and words that aren't twins are in different groups. Return the list of groups.
The groups can be in any order, and so can the words inside each group.
Examples
Example 1
- Input
- words = ["star", "rats", "note", "tone", "arts", "cat"]
- Output
- [["star", "rats", "arts"], ["note", "tone"], ["cat"]]
star, rats and arts share the letters a, r, s, t. note and tone share e, n, o, t. cat has no twin.
Example 2
- Input
- words = ["no", "on", "no"]
- Output
- [["no", "on", "no"]]
Repeated words stay in the result.
Example 3
- Input
- words = ["solo"]
- Output
- [["solo"]]
Rules
- Words use only lowercase letters a to z, and can be empty.
- There are between 1 and 10,000 words, each at most 20 letters long.
- The same word can appear more than once. Keep every copy.
Words on this page, in plain English (1)Open if any word is new to you
- Array (list)
- A list of values kept in order, inside square brackets. Like a row of numbered lockers.
Answer each question in your own words before you look at ours. Rough notes are fine: the point is to think before you type code. Your answers stay in this browser.
1.What goes in?
Name every input and what it looks like. Can it be empty? Sorted? Negative?
Stuck? Each hint gives a little more away. Try the problem again after each one.
This explains the whole solution.
You will learn the most by trying first, even if you don’t finish. But if this pattern is new to you, reading the walkthrough first is a fine way to learn it.
1. Understand the problem
This builds on Letter twins. There we checked whether two words are twins. Now we have a whole list, and must sort it into groups of twins. Every word belongs to exactly one group, even if it's a group of one.
2. Solve an example by hand
With ["star", "rats", "note", "tone", "arts", "cat"], you'd probably start a pile for star, put rats on it, start a new pile for note with tone, add arts to the first pile, and give cat its own pile.
But how did you decide rats goes on the star pile? You noticed they use the same letters. The program needs a way to turn that noticing into something it can look up.
3. The slow way
For each word, compare it with the first word of every existing group using the Letter twins check, and add it to the group that matches.
With 10,000 words that could be up to 50 million twin checks. That's O(n²) comparisons again.
4. Spot the pattern
This is group by a key. We need a key that is the same for every twin, and different for words that aren't twins. Here's the trick: sort each word's letters.
| Word | Sorted letters |
|---|---|
| star | arst |
| rats | arst |
| arts | arst |
| note | enot |
| tone | enot |
Twins always sort to the same text, and non-twins never do. The sorted letters are the perfect Map key.
5. The faster idea
For each word: work out its key (the sorted letters), find the group for that key in a Map (creating it if needed), and add the word. At the end, the Map's values are the groups.
Group words by their sorted letters
words
- key =
- –
groups (Set)
empty
function groupTheTwins(words) { const groups = new Map(); // sorted letters → words with those letters for (const word of words) { const key = [...word].sort().join(""); if (!groups.has(key)) { groups.set(key, []); } groups.get(key).push(word); } return [...groups.values()];}Start with an empty Map. Each key will be a word's letters in sorted order.
6. The code, line by line
const groups = new Map(); // sorted letters → words with those lettersKeys are sorted letters; values are arrays of the words in that group.
for (const word of words) { const key = [...word].sort().join("");[...word]splits the word into an array of letters,.sort()puts them in order, and.join("")glues them back into one string."star"becomes"arst".if (!groups.has(key)) { groups.set(key, []); }The first time we meet a key, start an empty group for it.
groups.get(key).push(word);Add the word to its group.
groups.get(key)returns the array itself, sopushchanges the array stored in the Map.return [...groups.values()];groups.values()gives the groups;[... ]turns them into a normal array.
Why a string key and not the sorted array? Two arrays are only equal if they are the same array, so ["a", "r", "s", "t"] from star and from rats would be different keys. Strings with the same text are always equal.
7. How fast is it?
For n words of up to k letters, each word is sorted once: O(n × k log k) time. Words here are short (20 letters at most), so this is close to O(n), much faster than comparing every pair. The Map holds every word once: O(n × k) memory.
Common mistakes
- Using the array from
[...word].sort()as the key. Arrays are compared by identity, not contents. Join it into a string. - Grouping by a Set of letters.
aabandabbboth use only the letters a and b, but they're not twins. Sorting keeps the amounts:aabvsabb. - Forgetting repeated words. If
noappears twice, both copies belong in the result.
Memorise the solution, once you understand it.
This shows the full solution, then helps you rebuild it from memory in four steps. Remembering it is what lets you write it again in an interview, or in a week. Your result goes into your reviews, so it comes back just before you'd forget.
Learn it by heart: Group the twins
Read the 11 lines slowly. For each one, say out loud what it does and why it is there. Then cover it and move on to step 2.
function groupTheTwins(words) { const groups = new Map(); // sorted letters → words with those letters for (const word of words) { const key = [...word].sort().join(""); if (!groups.has(key)) { groups.set(key, []); } groups.get(key).push(word); } return [...groups.values()];}