← Home

49. Group Anagrams

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
greedyC++Markdown
49

Let's make this one less mysterious. For 49. Group Anagrams, the solution in this repository is mainly a greedy solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: greedy.

The notes already sitting in the source point us in the right direction:

  • time: O(NKlogK), space: O(NK), K is the maximum length of string in "strs"

Guide

When?

Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are count.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(NK), space: O(NK)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 44 ms, faster than 61.55% of C++ online submissions for Group Anagrams.
02//Memory Usage: 19.1 MB, less than 73.13% of C++ online submissions for Group Anagrams.
03//time: O(NKlogK), space: O(NK), K is the maximum length of string in "strs"
04struct RetrieveValue
05{   
06    template <typename T>
07    typename T::second_type operator()(T keyValuePair) const
08    {   
09        return keyValuePair.second;
10    }
11};
12
13class Solution {
14public:
15    vector<vector<string>> groupAnagrams(vector<string>& strs) {
16        unordered_map<string, vector<string>> groups;
17        
18        for(string& str : strs){
19            string sorted = str;
20            sort(sorted.begin(), sorted.end());
21            groups[sorted].push_back(str);
22        }
23        
24        vector<vector<string>> ans;
25        transform(groups.begin(), groups.end(), back_inserter(ans), RetrieveValue());
26        
27        return ans;
28    }
29};
30
31//Approach 2: Categorize by Count(no sorting)
32//Runtime: 136 ms, faster than 7.61% of C++ online submissions for Group Anagrams.
33//Memory Usage: 29.1 MB, less than 5.97% of C++ online submissions for Group Anagrams.
34//time: O(NK), space: O(NK)
35
36struct RetrieveValue
37{   
38    template <typename T>
39    typename T::second_type operator()(T keyValuePair) const
40    {   
41        return keyValuePair.second;
42    }
43};
44
45class Solution {
46public:
47    vector<vector<string>> groupAnagrams(vector<string>& strs) {
48        unordered_map<string, vector<string>> groups;
49        
50        for(string& str : strs){
51            vector<int> count(26, 0);
52            for(char c : str){
53                count[c-'a']++;
54            }
55            
56            string scount = "";
57            for(int& e : count){
58                scount += (to_string(e)+"#");
59            }
60            
61            groups[scount].push_back(str);
62        }
63        
64        vector<vector<string>> ans;
65        
66        transform(groups.begin(), groups.end(), back_inserter(ans), RetrieveValue());
67        
68        return ans;
69    }
70};

Cost

Complexity

Time
O(NK), space: O(NK)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.