Back to DSA
Group Anagrams
mediumYou receive a collection of strings. Partition them into groups where every string in a group is an anagram of the others. Two strings are anagrams when one can be rearranged to form the other using every letter exactly once. The groups may be returned in any order.
Examples
Example 1:
Input:
words = ["listen","enlist","google","silent","goelgo"]Output:
[["listen","enlist","silent"],["google","goelgo"]]Explanation: 'listen', 'enlist', and 'silent' are mutual anagrams. 'google' and 'goelgo' form the other group.
Example 2:
Input:
words = ["a"]Output:
[["a"]]Explanation: A single string stands alone in its own group.
Hints
import java.util.*;
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for (String s : strs) {
char[] chars = s.toCharArray();
Arrays.sort(chars);
String key = new String(chars);
map.computeIfAbsent(key, k -> new ArrayList<>()).add(s);
}
return new ArrayList<>(map.values());
}
}Time complexity
O(n * k log k)Space complexity
O(n * k)