Scrivio Interview library
Arrays and hashingHashing and hash mapsReported 28 times · 15 min read · updated 14 November 2026

Group the words of a list so that anagrams are together.

1What it means to group anagrams

Imagine a bag of letter tiles, the kind used in word games. Take the word tea, tip its three tiles onto the table, and line them up in alphabetical order: a, e, t. Now do the same with eat, and with ate. All three give the same row of tiles, a e t. Two words are anagrams exactly when their tiles, lined up in order, look the same. Keep this picture in mind; the whole solution grows out of it.

In plain words, an anagram of a word uses exactly the same letters, each the same number of times, in any order. We are given a list of words and must return them in groups, so that every group holds words that are anagrams of each other, and no two groups are anagrams of each other.

We will use one example all the way through, the list [eat, tea, tan, ate, nat, bat]. Let us group it by hand. eat, tea and ate all use a, e and t. tan and nat use a, n and t. bat uses a, b and t, and no other word does. So the answer is [[eat, tea, ate], [tan, nat], [bat]].

Notice how you did that in your head. You did not hold eat up against every other word letter by letter. You noticed the letters each word uses and put words with the same letters together. That is the idea the fast solution will copy, and it is why this problem is smaller than it looks.

PictureThe six example words and the groups we want

Each cell is one word of the input list. The panel shows the groups the answer must contain.

  1. eat0tea1tan2ate3nat4bat5
    group 1
    [eat, tea, ate]
    group 2
    [tan, nat]
    group 3
    [bat]

    1The input is six words. Three of them use the letters a, e, t, two use a, n, t, and bat stands alone, so the answer has three groups.

What to assume

Is the comparison case-sensitive, and do spaces count?
We assume an exact comparison.
Are the words only lowercase a to z, or any characters?
Any characters.
Does the order of the groups matter?
We return groups in the order their first word appears, which makes the output easy to test.
Can the same word appear twice, or be empty?
Duplicates go into the same group, and the empty string forms a group of its own.

A careful candidate asks a few questions first. Is the comparison case-sensitive, and do spaces count? We assume an exact comparison. Are the words only lowercase a to z, or any characters? We write the main version for any characters and show a faster one for a to z. Does the order of the groups matter? We return groups in the order their first word appears, which makes the output easy to test. Can the same word appear twice, or be empty? Duplicates go into the same group, and the empty string forms a group of its own.

2How to recognise a grouping problem for a hash map

A beginner reading this for the first time usually thinks about comparing words. How do I check that two words are anagrams? Then I will check every pair. That is a natural start, and it does work, as the next section shows. But let us read the question again for its clues before we commit.

The first clue is the word group. We are not asked whether two particular words match; we are asked to sort many items into bins. Whenever items go into bins, the question to ask is what label to write on each bin, so that each item can find its own bin without looking at the other items.

The second clue is the kind of sameness. Anagrams are not equal strings, since eat and tea differ, but they are equal in a looser sense, the same letters in any order. When the sameness is looser than plain equality, we look for a way to turn each item into a standard form, called a canonical key. Canonical means the one agreed form. Every word in a group must produce the same key, and words from different groups must produce different keys. Our sorted tile row, a e t, is exactly such a key.

These clues point to the arrays and hashing pattern, and to its main tool, the hash map. A hash map works like the index at the back of a book: you look up a word and it tells you the page at once, without reading the book. In Java a HashMap stores pairs of key and value, and finding the value for a key takes about the same short time however many pairs it holds. Here the key is the sorted letters and the value is the list of words that share them. The rule to carry to new problems is this. To group items by a looser kind of equality, compute a canonical key for each item and let a hash map from key to group do the matching in one pass.

Some other patterns look possible. Sorting the whole list by key would also put anagrams next to each other, but it adds an O(n log n) sort that the map does not need. A trie, a tree of letters, could group sorted words too, but it is heavier than a map for no benefit. Two pointers and sliding windows work on runs inside one array, which is not what grouping is about.

3The brute force, comparing words with each other

The honest first attempt follows the beginner's instinct. Take the first word that is not yet in a group and start a new group with it. Then scan every later word that is still free, and if it is an anagram of the group's first word, add it and mark it as used. Repeat until every word is in a group. To test whether two words are anagrams, we compare their lengths and then count letters, adding one for each letter of the first word and subtracting one for each letter of the second; they are anagrams when every count ends at zero. This brute force is correct, and it is good to have it in mind.

Java
static List<List<String>> groupSlow(String[] words) {
List<List<String>> groups = new ArrayList<>();
boolean[] used = new boolean[words.length];
for (int i = 0; i < words.length; i++) {
if (used[i]) continue; // already in a group
List<String> g = new ArrayList<>(List.of(words[i]));
for (int j = i + 1; j < words.length; j++)
if (!used[j] && isAnagram(words[i], words[j])) { g.add(words[j]); used[j] = true; }
groups.add(g);
}
return groups;
}

Let us count on the example. eat is checked against tea, tan, ate, nat and bat, five checks, and its group becomes [eat, tea, ate]. tea is already used, so we skip it. tan is checked against nat and bat, two checks. ate and nat are used, and bat has nobody left to check. Seven checks in all. But that was lucky. If no two words were anagrams, every word would be checked against every later word: 5 + 4 + 3 + 2 + 1 = 15 checks for six words, and n(n - 1) / 2 for n words. Each check reads both words, up to L letters each, so the time is O(n squared times L). For 10,000 words that is about fifty million checks.

Where is the waste? Every check looks at two words together, so the work grows with the number of pairs. Yet whether a word belongs to a group depends only on its own letters. If we could compute something from each word alone, a label for its bin, we would never need to look at pairs at all. That something is the canonical key.

4Getting to one pass with a canonical key

Let us build the key from the tile picture. We turn the word into an array of characters, sort that array, and turn it back into a string. eat becomes aet, tea becomes aet, ate becomes aet. tan and nat both become ant, and bat becomes abt.

Here is the question a careful beginner asks. Could two words that are not anagrams ever produce the same sorted key? Let us think about what the key holds. The sorted string lists every letter of the word, each as many times as it appears. If two words give the same sorted string, they have the same letters with the same counts, which is exactly what being anagrams means. And if they are anagrams, sorting their identical bags of letters gives identical strings. So equal keys mean anagrams, and anagrams mean equal keys, in both directions.

With the key chosen, the grouping is one loop over the words. For each word we build its key, then ask the map for the list belonging to that key. Java has a method made for this, computeIfAbsent. If the key is not in the map yet, it creates a new empty list, stores it under the key, and returns it. If the key is already there, it returns the list that is there. Either way we add the word to the list we get back. When the loop ends, the map's values are the groups.

One small choice decides the order of the output. A plain HashMap gives back its values in an order that depends on the hashing, not on the input. A LinkedHashMap is a HashMap that also remembers the order in which keys were first added, so the groups come out in the order their first word appeared. That makes the output predictable and easy to test.

The mistake beginners most often make here is to build a key that records which letters a word uses but not how many times. A set of letters, for example, gives ab and abb the same key, though they are not anagrams. The sorted string keeps every repeated letter, so it does not have this problem.

5Watching the map fill up on the example

The picture runs the real loop on our six words. In each frame one word, marked w, is placed. The panel shows the word, its key, whether the key is new or already seen, and every list in the map at that moment. Earlier words that share the current key are highlighted, so you can see the group forming.

Notice that a word is never compared with another word. The only work per word is building its key and one lookup in the map.

Step throughFilling the map one word at a time

w is the word being placed. Earlier words that share its key are highlighted. The panel shows the key and every list in the map.

  1. eat0tea1tan2ate3nat4bat5
    word
    not started
    map
    empty

    1We start with an empty map. For each word we will build its key by sorting its letters, then put the word in the list for that key.

  2. eat0tea1tan2ate3nat4bat5w
    word
    eat
    key
    aet (new)
    aet
    [eat]

    2eat sorts to aet. The map has no aet yet, so computeIfAbsent makes a new empty list for it, and we add eat to that list.

  3. eat0tea1tan2ate3nat4bat5w
    word
    tea
    key
    aet (seen)
    aet
    [eat, tea]

    3tea also sorts to aet. This time the key is already there, so we get the existing list and add tea to it, next to eat.

  4. eat0tea1tan2ate3nat4bat5w
    word
    tan
    key
    ant (new)
    aet
    [eat, tea]
    ant
    [tan]

    4tan sorts to ant, a key we have not seen. A second list is made, and tan goes into it.

  5. eat0tea1tan2ate3nat4bat5w
    word
    ate
    key
    aet (seen)
    aet
    [eat, tea, ate]
    ant
    [tan]

    5ate sorts to aet once more, so it joins eat and tea. No word was ever compared with another word; only keys were looked up.

  6. eat0tea1tan2ate3nat4bat5w
    word
    nat
    key
    ant (seen)
    aet
    [eat, tea, ate]
    ant
    [tan, nat]

    6nat sorts to ant, so it joins tan in the second list.

  7. eat0tea1tan2ate3nat4bat5w
    word
    bat
    key
    abt (new)
    aet
    [eat, tea, ate]
    ant
    [tan, nat]
    abt
    [bat]

    7bat sorts to abt, a new key, so it starts a third list on its own.

  8. eat0tea1tan2ate3nat4bat5
    groups
    3
    aet
    [eat, tea, ate]
    ant
    [tan, nat]
    abt
    [bat]

    8Every word has been placed once. The map's values, in the order their keys first appeared, are the answer: [[eat, tea, ate], [tan, nat], [bat]].

Let us read the important frames back. The first frame for eat creates the aet list. The next one, for tea, finds aet already in the map, so tea joins eat without anyone checking tea against eat letter by letter. The key did the matching.

tan makes a second key, ant, and its list. When ate arrives, its key aet is found at once, and it joins the first group, even though four words have been seen since that group began. nat joins tan the same way, and bat starts a third list.

In the last frame the map holds three keys, in the order aet, ant, abt, because a LinkedHashMap remembers the order they first appeared. Its values are the answer, [[eat, tea, ate], [tan, nat], [bat]]. Six words, six keys built, six lookups, and no pair of words ever compared.

6The complete Java program

Here is the full program. groupAnagrams uses the sorted-letters key, and countKey shows a cheaper key for lowercase words, which we discuss below. main runs our example, a list holding only the empty string, words that share letters but not counts, and a check that two anagrams give the same count key. Each comment shows what that line prints.

Java
import java.util.*;
public class GroupAnagrams {
// Words that are anagrams share the same letters in sorted order, so that is the key.
static List<List<String>> groupAnagrams(String[] words) {
Map<String, List<String>> groups = new LinkedHashMap<>(); // keeps first-seen order
for (String w : words) {
char[] letters = w.toCharArray();
Arrays.sort(letters);
String key = new String(letters); // "eat" -> "aet"
groups.computeIfAbsent(key, k -> new ArrayList<>()).add(w);
}
return new ArrayList<>(groups.values());
}
// Alternative key for lowercase a-z: the 26 letter counts, O(L) instead of O(L log L).
static String countKey(String w) {
int[] count = new int[26];
for (char c : w.toCharArray()) count[c - 'a']++;
return Arrays.toString(count);
}
public static void main(String[] args) {
String[] words = {"eat", "tea", "tan", "ate", "nat", "bat"};
System.out.println(groupAnagrams(words)); // [[eat, tea, ate], [tan, nat], [bat]]
System.out.println(groupAnagrams(new String[] {""})); // [[]]
System.out.println(groupAnagrams(new String[] {"ab", "ba", "abb"})); // [[ab, ba], [abb]]
System.out.println(countKey("tea").equals(countKey("eat"))); // true
}
}

Let us read groupAnagrams in the order it runs. First we create the LinkedHashMap groups, from a String key to a List of words. Then for each word w we call w.toCharArray(), which gives a new array of its characters, so sorting it does not change the word itself. Arrays.sort puts the characters in order, and new String(letters) turns them back into the key, so eat becomes aet.

The next line does the grouping. computeIfAbsent(key, k -> new ArrayList<>()) returns the list stored for key, first creating an empty one if there was none, and .add(w) puts the word in it. The little expression k -> new ArrayList<>() is a lambda, a short piece of code handed to the method, which it runs only when the key is missing.

Finally, new ArrayList<>(groups.values()) copies the map's lists into a plain list of lists, in the order the keys first appeared. So main prints [[eat, tea, ate], [tan, nat], [bat]]. The empty string sorts to the empty key and forms one group, printed [[]]. And ab, ba and abb give [[ab, ba], [abb]], because abb has two b's.

countKey is the cheaper key. It counts how many times each of the 26 lowercase letters appears, using c - 'a' to turn a letter into a position from 0 to 25, and Arrays.toString turns the 26 counts into a string we can use as a map key. tea and eat give the same counts, so the last line prints true.

7How much it costs, and the cases at the edges

Let us count on the example first. We built six keys, each by sorting three letters, and made six map lookups. Now let n be the number of words and L the length of the longest word. Copying a word into a char array takes about L steps, and sorting it takes about L log L, because sorting is a little more than linear. Hashing a key of length L and comparing it in the map takes about L steps. So each word costs O(L log L), and the whole list costs O(n L log L) time.

The space is the map. It holds every word once, inside the lists, plus one key per group, so it stores at most about n times L characters, which is O(n L). With countKey instead of sorting, each word costs O(L) to count plus a fixed 26 to turn into a string, so the total time drops to O(n L), which is as good as it can be, since we must at least read every letter.

Comparing the approaches
ApproachTimeExtra space
Brute force: compare word with wordO(n^2 L)O(n L)
Sorted-letters key in a hash mapO(n L log L)O(n L)
Letter-count key, a to z onlyO(n L)O(n L)

The edge cases come out naturally. An empty list gives an empty result, because the loop never runs. The empty string sorts to the empty key and forms its own group. Duplicate words, such as eat twice, produce the same key and land in the same group. And if the comparison should ignore case or spaces, we change only how the key is built, lowercasing the word or removing spaces first, while still adding the original word to the group.

8Follow-up questions

How would you check whether just two strings are anagrams?

First compare their lengths, because anagrams must be the same length. Then use one array of 26 counts. For each letter of the first string add one to its count, and for each letter of the second subtract one. If every count ends at zero, the two strings used the same letters the same number of times. That is O(L) time and O(1) extra space. Sorting both strings and comparing them also works, in O(L log L).

Can we use a product of prime numbers as the key?

Yes, in principle. Give each letter its own prime, 2 for a, 3 for b, 5 for c and so on, and multiply the primes of a word's letters. Because every whole number splits into primes in only one way, anagrams and only anagrams get the same product. It is a clever idea, but the product overflows a long after a dozen or so letters, so real words need BigInteger, which is slower than the count key. It is worth mentioning, not worth using.

What changes if the words can contain any Unicode characters?

The sorted key still works, because sorting characters does not care which alphabet they come from. The 26-count key does not, since it assumes the letters a to z. For a large alphabet we could count with a HashMap from character to count, or a TreeMap so the counts come out in a fixed order, and turn that into the key. Characters outside the basic range, such as many emoji, take two Java chars each, so for full correctness we would sort code points rather than chars.

9Conclusion

We grouped anagrams by giving each word a canonical key, its letters in sorted order, the way letter tiles line up on a rack, and letting a LinkedHashMap from key to list collect the words that share a key. Each word is handled once, so the time is O(n L log L) with sorted keys, or O(n L) with a key of 26 letter counts, and the space is O(n L). The key must keep letter counts, not only which letters appear. The clue to remember is grouping by a looser kind of sameness: compute a canonical key and let a hash map do the matching.

What to say in the interviewAbout 90 seconds aloud

Open with

Two words are anagrams when they use the same letters the same number of times, so I want a key that is equal for anagrams and different otherwise.

Then, if they want more

The brute force compares each word with every later word using letter counts, which is O(n squared times L). Since this is grouping by a looser equality, I use the hashing pattern with a canonical key. The simplest key is the word with its letters sorted: eat, tea and ate all become a, e, t.

I build a LinkedHashMap from key to a list of words. For each word I sort its characters, make a string, and use computeIfAbsent to get or create the list for that key, then add the word. At the end the map's values are the groups, in the order their first words appeared.

For n words of length up to L, sorting each word costs L log L, so the total is O(n L log L) time and O(n L) space. If the words are only lowercase letters, I can make the key from the 26 letter counts, which is O(L) per word, so O(n L) overall.

The key must keep counts, not just a set of letters, or ab and abb would be grouped together. The empty string gets an empty key and its own group.

About this answer

Last updated
14 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 28 times in that collection. How it is counted
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Group the words of a list so that anagrams are together.": https://scrivio-interview-library.netlify.app/data-structures/solutions/group-the-words-of-a-list-so-that-anagrams-are-together-1c0832/