#49
Medium Algorithms Group anagrams
Array Hash Table String Sorting
72.2% acceptance
Jan 12, 2026
21889
750
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
Solution
Rust
Time O(n²)
Space O(n)
impl Solution {
pub fn group_anagrams(strs: Vec<String>) -> Vec<Vec<String>> {
use std::collections::HashMap;
let mut map: HashMap<[u8; 26], Vec<String>> = HashMap::new();
for s in strs {
// Create frequency count array as key (faster than sorting)
let mut count = [0u8; 26];
for byte in s.bytes() {
count[(byte - b'a') as usize] += 1;
}
// Add the original string to the group
map.entry(count).or_insert_with(Vec::new).push(s);
}
// Convert the HashMap values to a vector
map.into_values().collect()
}
}