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;
}
};
Difficulty
and has an acceptance rate of about 73% (6+ million submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
- Sorting
- String
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 242: Valid Anagram
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
Extra
- 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