Group Anagrams

75.4k
0

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

  1. Initialise an empty list groups to store the anagram groups.

  2. For each word in strs, set placed to false.

  3. Traverse the existing groups and compare word with the first word of each group.

  4. If their lengths match, sort copies of both words and check whether the sorted forms are equal.

  5. If they match, append word to that group, set placed to true, and stop checking further groups.

  6. If placed is still false, create a new group containing word.

  7. Return groups after processing all words.

Dry Run

Group anagrams

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

  1. Initialise an empty hash map groupedWords to store a list of words for each sorted key.

  2. Traverse each word in strs.

  3. Copy word into key and sort its characters.

  4. Append the original word to groupedWords[key]. If the key is new, the map creates an empty list before insertion.

  5. After processing all words, create an empty result list groups.

  6. Traverse the hash map and append each stored list to groups.

  7. Return groups.

Dry Run

Group anagrams

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

  1. Initialise an empty hash map groupedWords to store groups by their frequency keys.

  2. For each word in strs, initialise a frequency array of size 26 with zeros.

  3. Traverse the word. For each character ch, increment frequency[ch - 'a'].

  4. Build a key from all 26 counts in alphabetical order, separating them with a delimiter.

  5. Append the original word to the group associated with that key. Create an empty group first if the key is new.

  6. After processing all words, collect the lists stored in the hash map.

  7. Return the collected groups.

Dry Run

p

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.

ArraysStringHashingSorting

Read Similar Blogs

Comments0