DSA AnimatorREVISION VIDEOS
← Back to problems
New

Group Anagrams — LeetCode 49 video explanation

You get a list of words. Group the words that are anagrams of each other. Anagrams use the same letters in a different order.

Loading videos…

DSA Animator › DSA Revision › Strings › Group Anagrams

Key moments in the Group Anagrams video

0:03Problem0:11Example0:19Brute force0:25Key idea0:37Dry run0:57Code1:13Takeaway

What you will learn

Remember: anagrams share one canonical key, their sorted letters. Group by that key in a hash map. The video solves Group Anagrams (LeetCode 49, Medium) with the Hash Map pattern from the Strings topic, and you can replay every step in the interactive Group Anagrams animation.

Group Anagrams video transcript

Problem

You get a list of words. Group the words that are anagrams of each other. Anagrams use the same letters in a different order.

Example

eat, tea, tan, ate, nat and bat. eat, tea and ate form one group. tan and nat form a second group. And bat stands alone.

Brute force

Comparing every word with every other word is O of n squared. For thousands of words, that is far too slow.

Key idea

Sort the letters of an anagram, and they all become the same string. eat, tea and ate all sort to a e t. So use the sorted word as the hash map key. Every word goes into the list for its key.

Dry run

eat has the key a e t, so a new list starts. tea also has the key a e t, so it joins that list. tan has the key a n t, a new list. ate has the key a e t, so it joins the first list. nat has the key a n t, so it joins the second list. bat has the key a b t, a third list. The three lists in the map are the answer.

Code

In code, create a map from a string key to a list of words. For each word, sort its letters to build the key. computeIfAbsent gets or creates the list, and the word is added to it. Finally, return the map values. Time is O of n times k log k, where k is the word length.

Takeaway

Remember: anagrams share one canonical key, their sorted letters. Group by that key in a hash map.

More Strings revision videos

← All 185 DSA revision videos