vector<vector<string>> groupAnagrams(vector<string>& strs) {
auto isAnagram = [](string a, string b) { sort(a.begin(), a.end()); sort(b.begin(), b.end()); return a == b; };
vector<vector<string>> groups;
for (const string& word : strs) {
bool placed = false;
for (auto& group : groups) {
if (isAnagram(group[0], word)) {
group.push_back(word);
placed = true;
break;
}
}
if (!placed) groups.push_back({word});
}
return groups;
}
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> groups = new ArrayList<>();
for (String word : strs) {
boolean placed = false;
for (List<String> group : groups) {
if (isAnagram(group.get(0), word)) {
group.add(word);
placed = true;
break;
}
}
if (!placed) groups.add(new ArrayList<>(List.of(word)));
}
return groups;
}
private boolean isAnagram(String a, String b) {
char[] x = a.toCharArray(), y = b.toCharArray();
Arrays.sort(x); Arrays.sort(y);
return Arrays.equals(x, y);
}
def group_anagrams(strs: list[str]) -> list[list[str]]:
def is_anagram(a: str, b: str) -> bool: return sorted(a) == sorted(b)
groups: list[list[str]] = []
for word in strs:
placed = False
for group in groups:
if is_anagram(group[0], word):
group.append(word)
placed = True
break
if not placed: groups.append([word])
return groups
function groupAnagrams(strs: string[]): string[][] {
const isAnagram = (a: string, b: string) => [...a].sort().join('') === [...b].sort().join('');
const groups: string[][] = [];
for (const word of strs) {
let placed = false;
for (const group of groups) {
if (isAnagram(group[0], word)) {
group.push(word);
placed = true;
break;
}
}
if (!placed) groups.push([word]);
}
return groups;
}
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> buckets;
for (const string& word : strs) {
string key = word; sort(key.begin(), key.end());
if (!buckets.count(key)) buckets[key] = {};
buckets[key].push_back(word);
}
vector<vector<string>> out;
for (auto& kv : buckets) out.push_back(kv.second);
return out;
}
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> buckets = new HashMap<>();
for (String word : strs) {
char[] chars = word.toCharArray(); Arrays.sort(chars);
String key = new String(chars);
if (!buckets.containsKey(key)) buckets.put(key, new ArrayList<>());
buckets.get(key).add(word);
}
return new ArrayList<>(buckets.values());
}
def group_anagrams(strs: list[str]) -> list[list[str]]:
buckets: dict[str, list[str]] = {}
for word in strs:
key = ''.join(sorted(word))
if key not in buckets: buckets[key] = []
buckets[key].append(word)
return list(buckets.values())
function groupAnagrams(strs: string[]): string[][] {
const buckets = new Map<string, string[]>();
for (const word of strs) {
const key = [...word].sort().join('');
if (!buckets.has(key)) buckets.set(key, []);
buckets.get(key)!.push(word);
}
return [...buckets.values()];
}
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> buckets;
for (const string& word : strs) {
array<int, 26> counts{};
for (char ch : word) counts[ch - 'a']++;
string key; for (int c : counts) key += to_string(c) + ',';
auto it = buckets.find(key);
if (it != buckets.end()) it->second.push_back(word);
else buckets[key] = {word};
}
vector<vector<string>> out;
for (auto& kv : buckets) out.push_back(kv.second);
return out;
}
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> buckets = new HashMap<>();
for (String word : strs) {
int[] counts = new int[26];
for (char ch : word.toCharArray()) counts[ch - 'a']++;
String key = Arrays.toString(counts);
List<String> bucket = buckets.get(key);
if (bucket != null) bucket.add(word);
else buckets.put(key, new ArrayList<>(List.of(word)));
}
return new ArrayList<>(buckets.values());
}
def group_anagrams(strs: list[str]) -> list[list[str]]:
buckets: dict[str, list[str]] = {}
for word in strs:
counts = [0] * 26
for ch in word: counts[ord(ch) - 97] += 1
key = ','.join(map(str, counts))
bucket = buckets.get(key)
if bucket is not None: bucket.append(word)
else: buckets[key] = [word]
return list(buckets.values())
function groupAnagrams(strs: string[]): string[][] {
const buckets = new Map<string, string[]>();
for (const word of strs) {
const counts = new Array<number>(26).fill(0);
for (const ch of word) counts[ch.charCodeAt(0) - 97]++;
const key = counts.join(',');
const bucket = buckets.get(key);
if (bucket) bucket.push(word);
else buckets.set(key, [word]);
}
return [...buckets.values()];
}
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> buckets;
uint16_t counts[26];
for (const string& word : strs) {
fill(begin(counts), end(counts), 0);
for (size_t i = 0; i < word.size(); i++) {
int c = word[i] - 'a';
if (c < 0 || c > 25) throw out_of_range("lowercase a-z only");
counts[c]++;
}
string key(reinterpret_cast<const char*>(counts), sizeof(counts));
auto it = buckets.find(key);
if (it != buckets.end()) it->second.push_back(word);
else buckets[key] = {word};
}
vector<vector<string>> out;
for (auto& kv : buckets) out.push_back(kv.second);
return out;
}
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> buckets = new HashMap<>();
char[] counts = new char[26]; // char as an unsigned 16-bit counter
for (String word : strs) {
Arrays.fill(counts, (char) 0);
for (int i = 0; i < word.length(); i++) {
int c = word.charAt(i) - 'a';
if (c < 0 || c > 25) throw new IllegalArgumentException("lowercase a-z only");
counts[c]++;
}
String key = new String(counts);
List<String> bucket = buckets.get(key);
if (bucket != null) bucket.add(word);
else buckets.put(key, new ArrayList<>(List.of(word)));
}
return new ArrayList<>(buckets.values());
}
def group_anagrams(strs: list[str]) -> list[list[str]]:
buckets: dict[tuple[int, ...], list[str]] = {}
counts = [0] * 26
for word in strs:
for i in range(26): counts[i] = 0
for i in range(len(word)):
c = ord(word[i]) - 97
if c < 0 or c > 25: raise ValueError('lowercase a-z only')
counts[c] += 1
key = tuple(counts)
bucket = buckets.get(key)
if bucket is not None: bucket.append(word)
else: buckets[key] = [word]
return list(buckets.values())
function groupAnagrams(strs: string[]): string[][] {
const buckets = new Map<string, string[]>();
const counts = new Uint16Array(26);
for (const word of strs) {
counts.fill(0);
for (let i = 0; i < word.length; i++) {
const c = word.charCodeAt(i) - 97;
if (c < 0 || c > 25) throw new RangeError('lowercase a-z only');
counts[c]++;
}
const key = String.fromCharCode(...counts);
const bucket = buckets.get(key);
if (bucket !== undefined) bucket.push(word);
else buckets.set(key, [word]);
}
return Array.from(buckets.values());
}