Problem Statement
Given an array strs containing N strings made of lowercase English letters, place all anagrams inside the same group.
Anagrams contain identical character frequencies, although character order may differ. Return all groups in any order.
Example 1
Input strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
Output [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]
Explanation "eat", "tea", and "ate" contain the same letters and form one group. Similarly, "tan" and "nat" form another group. "bat" has no other anagram in the input, so it forms its own group. The groups can appear in any order.
Example 2
Input: strs = [""]
Output: [[""]]
Explanation: The empty string forms a valid group containing one string.
Example 3
Input: strs = ["a"]
Output: [["a"]]
Explanation: A single string forms one anagram group.
Brute Force Approach
Process the words one at a time. For each word, check whether it is an anagram of a word in an existing group. If a matching group exists, add it there. Otherwise, create a new group containing that word.
Use the first word of each group as its representative. Since every word in a group is an anagram of the others, comparing with one representative is enough.
To check whether two words are anagrams, first compare their lengths. If the lengths differ, they cannot be anagrams. Otherwise, sort copies of both words and compare them. For example, "eat" and "tea" both become "aet" after sorting, so they belong to the same group. Sorting copies preserves the original words in the output.
Algorithm
Initialise an empty list
groupsto store the anagram groups.For each
wordinstrs, setplacedtofalse.Traverse the existing groups and compare
wordwith the first word of each group.If their lengths match, sort copies of both words and check whether the sorted forms are equal.
If they match, append
wordto that group, setplacedtotrue, and stop checking further groups.If
placedis stillfalse, create a new group containingword.Return
groupsafter processing all words.
Dry Run

Group anagrams
Solution
#include <bits/stdc++.h>using namespace std;class Solution {private: /* Checks whether two strings are anagrams. */ bool isAnagram(const string& first, const string& second) { // Different lengths cannot form anagrams. if (first.length() != second.length()) { return false; } // Sort separate copies for direct comparison. string sortedFirst = first; string sortedSecond = second; sort(sortedFirst.begin(), sortedFirst.end()); sort(sortedSecond.begin(), sortedSecond.end()); return sortedFirst == sortedSecond; }public: /* Groups anagrams through pairwise group checks. */ vector<vector<string>> groupAnagrams(vector<string>& strs) { vector<vector<string>> groups; // Place every word into a matching group. for (const string& word : strs) { bool placed = false; // Compare against one representative per group. for (vector<string>& group : groups) { if (isAnagram(word, group[0])) { group.push_back(word); placed = true; break; } } // Start a new group after no match. if (!placed) { groups.push_back({word}); } } return groups; }};// Driver code to execute the solution.int main() { vector<string> strs = {"eat", "tea", "tan", "ate", "nat", "bat"}; Solution solution; vector<vector<string>> answer = solution.groupAnagrams(strs); // Print every generated group. for (const vector<string>& group : answer) { cout << "["; for (int i = 0; i < (int)group.size(); i++) { cout << '"' << group[i] << '"'; if (i + 1 < (int)group.size()) { cout << ", "; } } cout << "]" << endl; } return 0;}Complexity Analysis
Time Complexity: O(N² × K log K) in the worst case, where N represents the number of strings and K represents the maximum string length. A word can be compared with O(N) existing groups, and every comparison can sort two strings in O(K log K) time.
Space Complexity: O(N × K) including the returned groups. Excluding output storage, O(K) temporary space is required for sorted copies during one anagram comparison.
Better Approach
Anagrams contain the same characters with the same frequencies, so sorting them produces the same string. For example, "eat", "tea", and "ate" all become "aet" after sorting. We can use this sorted string as a key to identify their group.
Use a hash map where each key is a sorted string and its value is a list of the original words belonging to that group. For each word, sort a copy and use the resulting key to find its group directly.
For example, "eat" creates the group under "aet". When "tea" and "ate" are processed, their sorted keys are also "aet", so they join the same group. Sorting a copy preserves each original word in the output.
After processing all words, collect the lists stored in the hash map. These lists form the anagram groups, which can appear in any order.
Algorithm
Initialise an empty hash map
groupedWordsto store a list of words for each sorted key.Traverse each
wordinstrs.Copy
wordintokeyand sort its characters.Append the original
wordtogroupedWords[key]. If the key is new, the map creates an empty list before insertion.After processing all words, create an empty result list
groups.Traverse the hash map and append each stored list to
groups.Return
groups.
Dry Run

Group anagrams
Solution
#include <bits/stdc++.h>using namespace std;class Solution {public: /* Groups anagrams with sorted-string keys. */ vector<vector<string>> groupAnagrams(vector<string>& strs) { unordered_map<string, vector<string>> groupedWords; // Build one sorted key for every word. for (const string& word : strs) { string key = word; sort(key.begin(), key.end()); // Store the original word under the key. groupedWords[key].push_back(word); } vector<vector<string>> groups; // Extract all groups from the Hash Map. for (const auto& entry : groupedWords) { groups.push_back(entry.second); } return groups; }};// Driver code to execute the solution.int main() { vector<string> strs = {"eat", "tea", "tan", "ate", "nat", "bat"}; Solution solution; vector<vector<string>> answer = solution.groupAnagrams(strs); // Print every generated group. for (const vector<string>& group : answer) { cout << "["; for (int i = 0; i < (int)group.size(); i++) { cout << '"' << group[i] << '"'; if (i + 1 < (int)group.size()) { cout << ", "; } } cout << "]" << endl; } return 0;}Complexity Analysis
Time Complexity: O(N × K log K) on average, where N represents the number of strings and K represents the maximum string length. Every string is sorted once, and each Hash Map operation requires average O(1) access after key processing.
Space Complexity: O(N × K), because the Hash Map stores sorted keys and all grouped strings. The returned groups also contain up to N × K characters.
Optimal Approach
Anagrams contain each letter the same number of times. Since the words contain only lowercase English letters, we can represent each word using a frequency array of size 26. Each position stores the count of one letter, from 'a' through 'z'.
For example, "eat", "tea", and "ate" each contain one 'a', one 'e', and one 't'. Their frequency arrays are identical, so we can use those counts to place them in the same group.
Convert each frequency array into a string key and use a hash map to store the original words under that key. Separate the counts with a delimiter, such as #. Without separators, counts like 1, 10 and 11, 0 would both become "110". Separators make them "1#10" and "11#0".
Counting visits each character once, taking O(K) time for a word of length K. Building the key uses exactly 26 counts. After processing all words, collect the groups stored in the hash map.
Algorithm
Initialise an empty hash map
groupedWordsto store groups by their frequency keys.For each
wordinstrs, initialise a frequency array of size26with zeros.Traverse the word. For each character
ch, incrementfrequency[ch - 'a'].Build a key from all
26counts in alphabetical order, separating them with a delimiter.Append the original
wordto the group associated with that key. Create an empty group first if the key is new.After processing all words, collect the lists stored in the hash map.
Return the collected groups.
Dry Run

p
Solution
#include <bits/stdc++.h>using namespace std;class Solution {private: /* Builds a key from lowercase character counts. */ string buildKey(const string& word) { array<int, 26> frequency{}; // Count every lowercase English letter. for (char character : word) { frequency[character - 'a']++; } string key; // Separate counts to avoid ambiguous keys. for (int count : frequency) { key.push_back('#'); key += to_string(count); } return key; }public: /* Groups anagrams with frequency keys. */ vector<vector<string>> groupAnagrams(vector<string>& strs) { unordered_map<string, vector<string>> groupedWords; // Build one frequency key for every word. for (const string& word : strs) { string key = buildKey(word); // Store the original word under the key. groupedWords[key].push_back(word); } vector<vector<string>> groups; // Extract all groups from the Hash Map. for (const auto& entry : groupedWords) { groups.push_back(entry.second); } return groups; }};// Driver code to execute the solution.int main() { vector<string> strs = {"eat", "tea", "tan", "ate", "nat", "bat"}; Solution solution; vector<vector<string>> answer = solution.groupAnagrams(strs); // Print every generated group. for (const vector<string>& group : answer) { cout << "["; for (int i = 0; i < (int)group.size(); i++) { cout << '"' << group[i] << '"'; if (i + 1 < (int)group.size()) { cout << ", "; } } cout << "]" << endl; } return 0;}Complexity Analysis
Time Complexity: O(N × K) on average, where N represents the number of strings and K represents the maximum string length. Every character is counted once, and building the fixed 26-position key requires constant alphabet work per string.
Space Complexity: O(N × K) including the returned groups. The Hash Map additionally stores one fixed-alphabet signature per distinct anagram group.
Interview follow-up Questions
Anagrams contain the same characters with the same frequencies. Sorting them produces the same string, which identifies their group.
Be the first to add a comment.