Loading…
Loading…
Given an array of strings strs, group together the strings that are anagrams of each other, and return the groups in any order.
Two strings are anagrams if they contain the same characters with the same counts, for example "eat", "tea" and "ate".
Input: ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]] (any order of groups and of words within groups)
Example 1
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
1 <= strs.length <= 10^40 <= strs[i].length <= 100Sort each string — anagrams produce the same sorted key. Use a HashMap<String, List<String>> keyed by that sorted string.
An alternative key avoids sorting entirely: encode each string's 26-letter frequency COUNT directly as the key (e.g. a delimited count string) — removes the O(k log k) sort per string, dropping to O(k).
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); // anagrams share the same sorted key
String key = new String(chars);
map.computeIfAbsent(key, k -> new ArrayList<>()).add(s);
}
return new ArrayList<>(map.values());
}Time: O(n * k log k) where k = max string length · Space: O(n*k)