Problem 49

Abstract / Summary

Group words that are anagrams of each other together into lists.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0049.cpp

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map<string, vector<string>> groups;

        for (auto& s : strs)
        {
            auto original = s;
            sort(s.begin(), s.end());
            groups[s].push_back(original);
        }

        vector<vector<string>> result;
        for (auto& g : groups)
            result.emplace_back(g.second);
        return result;
    }
};
18 lines | 470 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 73% (6+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
  • Sorting
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single public method groupAnagrams. The method receives a mutable reference to a vector of strings and returns a vector of string vectors, where each inner vector contains strings that are anagrams of one another. The algorithm proceeds by normalizing each input string, using the normalized form as a key in an unordered map, and then collecting the grouped values into the final result.

Key Steps

The first major step creates a hash map that will hold groups of anagrams. The map’s key is a string representing the sorted characters of an original word, and the value is a vector that accumulates the original words that share this sorted representation.

unordered_map<string, vector<string>> groups;

The core loop iterates over each string in the input vector. For each string, a copy of the original value is saved, the string itself is sorted in-place, and the sorted version is used to index the map. The original (unsorted) string is then appended to the corresponding bucket.

for (auto& s : strs)
{
    auto original = s;
    sort(s.begin(), s.end());
    groups[s].push_back(original);
}

After the map is fully populated, a second loop extracts the grouped vectors from the map and moves them into the result container. The use of emplace_back constructs each inner vector directly in the result, avoiding an extra copy.

vector<vector<string>> result;
for (auto& g : groups)
    result.emplace_back(g.second);
return result;

Edge Cases Handled

The algorithm gracefully handles an empty input vector. In that scenario the first loop never executes, the map remains empty, and the second loop produces an empty result vector, which correctly represents that there are no anagram groups.

When the input contains a single string, the sorting step reduces the string to itself, the map receives a single entry, and the final result consists of one inner vector containing that single string. This demonstrates correct handling of minimal non-empty inputs.

Strings that consist of a single character are also correctly processed. Sorting a one-character string leaves it unchanged, and such strings are grouped together if they share the same character. The map key for each distinct character is the character itself, ensuring proper grouping.

The code tolerates duplicate strings in the input. Each occurrence is treated independently: the original string is saved before sorting, and the duplicate is added to the same bucket as any other identical anagram. Consequently, the result may contain repeated entries within a group, reflecting the multiplicity of the input.

Performance Optimizations

The implementation leverages in-place sorting of each string (sort(s.begin(), s.end())) rather than creating a separate sorted copy. This reduces temporary allocations and keeps the memory footprint low during the grouping phase.

Using an unordered_map provides average-case constant-time insertion and lookup for the sorted keys. This choice avoids the logarithmic overhead associated with ordered maps and accelerates the grouping of large input sets.

The final collection step employs emplace_back to construct each group directly inside the result vector. This avoids an extra copy or move of the inner vectors, which can be significant when groups contain many strings.

By storing the original string before sorting (auto original = s;), the algorithm ensures that the map’s key remains the sorted representation while the original value is preserved for output. This avoids the need to reconstruct the original string after sorting, eliminating unnecessary work.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big pile of toy blocks, but each block has letters written on it to spell out a word. Some words are special because they are anagrams, which means they use the exact same letters in a different order, like the word eat and the word tea.

To group these words together, think of a magical sorting machine. This machine looks at every word in the pile one by one. For each word, it takes all the letters inside and puts them in alphabetical order. So, if a word is tea, the machine rearranges the letters to spell aet.

After the letters are in order, the machine looks for a cubbyhole labeled with that exact same alphabetical code. Since eat also rearranges to spell aet, it gets placed into the same cubbyhole as tea. Once every word has been sorted and placed into its matching cubbyhole, all the words that are anagrams end up sitting together in their own little groups. Finally, the machine collects all these groups of words and puts them into a bigger box to be organized neatly.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.89 | σ = 0.87

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Rust C# Go TS
LeetcodeHelp C++ Java Python
MemoryLimitExceeded C++ Python
Progiez C++ Java Python
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
bujosa Rust
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
everthis JS
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lennylxx C++
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
martianoff Scala
muhammadfarhankt Go
pruthvikp Python
qiyuangong Java
ruoru Rust
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
yuanliu666 Kotlin
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
bujosa Rust
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C++
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
martianoff Scala
muhammadfarhankt Go
pruthvikp Python
qiyuangong Java
ruoru Rust
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
yuanliu666 Kotlin
zfang399 C++
60 links | 44 authors | 12 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Group Anagrams - Leetcode 49 - Hashmaps & Sets (Python)'
Greg Hogg 8 mins
Group Anagrams - Leetcode 49 - Hashmaps & Sets (Python)
YouTube video 'Group Anagrams | using sorting | Google | Leetcode 49'
codestorywithMIK 12 mins
Group Anagrams | using sorting | Google | Leetcode 49
YouTube video 'Group Anagrams - LeetCode 49 - Java Solution.'
Java2Novice 6 mins
Group Anagrams - LeetCode 49 - Java Solution.
YouTube video 'LeetCode #49: Group Anagrams | Facebook Coding Interview | Google Coding Interview'
Knowledge Center 12 mins
LeetCode #49: Group Anagrams | Facebook Coding Interview | Google Coding Interview
YouTube video 'Group Anagrams - LeetCode 49 - Python'
Deepti Talesra 17 mins
Group Anagrams - LeetCode 49 - Python
YouTube video 'Group Anagrams - LeetCode 49 - JavaScript'
AlgoJS 5 mins
Group Anagrams - LeetCode 49 - JavaScript
YouTube video '[Java] Leetcode 49. Group Anagrams [String #2]'
Eric Programming 10 mins
[Java] Leetcode 49. Group Anagrams [String #2]
YouTube video 'Group Anagrams - LeetCode 49 - Blind 75 - Coding Interview'
One Code Man 10 mins
Group Anagrams - LeetCode 49 - Blind 75 - Coding Interview
YouTube video '49. Group anagrams || NEETCODE 150'
TechWithSaumya 20 mins
49. Group anagrams || NEETCODE 150
YouTube video 'Group Anagrams | Leetcode 49 | String HashMap | Google Amazon'
Naresh Gupta 10 mins
Group Anagrams | Leetcode 49 | String HashMap | Google Amazon
YouTube video 'LEETCODE 49 - GROUP ANAGRAMS [PYTHON]'
Cracking FAANG 11 mins
LEETCODE 49 - GROUP ANAGRAMS [PYTHON]
YouTube video 'Leetcode 49: Group Anagrams in Telugu | Hashing with Sorted Keys | Python DSA | SRKCodes'
Srk Codes 9 mins
Leetcode 49: Group Anagrams in Telugu | Hashing with Sorted Keys | Python DSA | SRKCodes
YouTube video 'Group Anagrams - LeetCode #49 - C++'
Sean Chuah 4 mins
Group Anagrams - LeetCode #49 - C++
YouTube video 'LeetCode 49 | Group Anagrams | Solution Explained (Java)'
Xavier Elon 6 mins
LeetCode 49 | Group Anagrams | Solution Explained (Java)
YouTube video 'Group Anagrams | Leetcode 49 | Live coding session 🔥🔥🔥'
Coding Decoded 6 mins
Group Anagrams | Leetcode 49 | Live coding session 🔥🔥🔥
YouTube video 'Group Anagrams - HashMap - Blind 75 - Leetcode 49 - Python'
CheatCode Ninja 6 mins
Group Anagrams - HashMap - Blind 75 - Leetcode 49 - Python
YouTube video '49. Group Anagrams | HashMap | JavaScript | LeetCode Daily Challenge'
LeetCodeWithMonu 15 mins
49. Group Anagrams | HashMap | JavaScript | LeetCode Daily Challenge
YouTube video 'Daily Leetcode #941: Oct 28, 2022 - 49. Group Anagrams'
Programming Live with Larry 3 mins
Daily Leetcode #941: Oct 28, 2022 - 49. Group Anagrams
YouTube video 'Group Anagrams - Leetcode 49 Solution'
Coding with Krp Ajay 10 mins
Group Anagrams - Leetcode 49 Solution
YouTube video 'LeetCode 49: Group Anagrams | C# Solution | Hash Table & Sorting'
Code Scribbler 8 mins
LeetCode 49: Group Anagrams | C# Solution | Hash Table & Sorting
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

19 easy 42 medium 2 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality