Group Anagrams

Group strings that are anagrams of each other — hash map keyed by sorted form.

Medium
Time O(N * L log L) Space O(N * L)
LeetCode
2 min read
hash-map sorting strings

Problem#

Given an array of strings, group those that are anagrams of each other into the same sub-list.

Examples#

  • ["eat","tea","tan","ate","nat","bat"][["bat"],["nat","tan"],["ate","eat","tea"]].

Constraints#

  • 1 <= strs.length <= 10^4, 0 <= strs[i].length <= 100.

Hints#

Hint
All anagrams share the same sorted character sequence — group on that.

Approach#

For each string, compute its sorted copy (canonical anagram form) and bucket the original by that key. Output the buckets.

Solution#

Group Anagrams
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> groups;
for (auto& s : strs) {
string k = s;
sort(k.begin(), k.end());
groups[k].push_back(s);
}
vector<vector<string>> ans;
ans.reserve(groups.size());
for (auto& [_, v] : groups) ans.push_back(std::move(v));
return ans;
}
};

Editorial#

Sorting each string gives an O(L log L) canonical form — clean and concise. For tighter constants, replace the sorted key with the count signature "a3b1c2..." for O(L) keying. Both correctly cluster anagrams.

Complexity#

  • Time: O(N * L log L).
  • Space: O(N * L).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.