49. Group Anagrams
Asked at 75Amazon80Apple74Microsoft70Bloomberg70Meta61Google58Smartsheet100HashedIn90Squarepoint Capital85Walmart Labs85EPAM Systems84Nvidia82Oracle81Wipro80Visa78Deloitte71Infosys66CrowdStrike65tcs57Booking.com50Avito100blinkit100Adobe96Yelp94Workday92Zoho90Okta89Nike89Wissen Technology88Disney88DP world88Sigmoid87Expedia84FreshWorks81Nutanix80UBS78Millennium76Docusign74SAP73Autodesk69Instacart69IBM69Coupang68athenahealth68PayPal67Anduril66Dell66Grab66jio65Palo Alto Networks65Siemens65FactSet65MakeMyTrip65BlackRock64Morgan Stanley64Twilio64PhonePe64eBay64Whatnot63Yandex63Uber62HCL60Affirm60josh technology58Salesforce57Goldman Sachs57Accolite55Upstart54Capgemini52TikTok46Cisco45Snap45Accenture44Intuit43Atlassian34
Problem
Group the strings in strs so that words that are anagrams of each other end up in the same group. Groups and the words inside them may be in any order.
Example: ["eat","tea","tan","ate","nat","bat"] → [["bat"],["nat","tan"],["ate","eat","tea"]]
Constraints: up to 10⁴ strings of length ≤ 100, lowercase letters.
Every anagram shares a canonical key: the sorted word (O(k log k)) or the 26-letter count tuple (O(k)). Group words by key.
"eat" -> key "aet" ┐
"tea" -> key "aet" ├─> ["eat","tea","ate"]
"ate" -> key "aet" ┘
"tan" -> key "ant" ──> ["tan","nat"] ...
Complexity: O(n·k) with count keys (n words, length k).
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
groups = defaultdict(list)
for w in strs:
key = [0] * 26
for ch in w:
key[ord(ch) - 97] += 1
groups[tuple(key)].append(w)
return list(groups.values())
res = Solution().groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"])
assert sorted(sorted(g) for g in res) == [["ate", "eat", "tea"], ["bat"], ["nat", "tan"]]
assert Solution().groupAnagrams([""]) == [[""]]
assert Solution().groupAnagrams(["a"]) == [["a"]]
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> groups = new HashMap<>();
for (String w : strs) {
char[] c = w.toCharArray();
Arrays.sort(c); // canonical key
groups.computeIfAbsent(new String(c), k -> new ArrayList<>()).add(w);
}
return new ArrayList<>(groups.values());
}
}
func groupAnagrams(strs []string) [][]string {
groups := map[[26]int][]string{} // letter counts are a valid map key
for _, w := range strs {
var key [26]int
for _, ch := range w {
key[ch-'a']++
}
groups[key] = append(groups[key], w)
}
res := make([][]string, 0, len(groups))
for _, g := range groups {
res = append(res, g)
}
return res
}