49. Group Anagrams

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.


Example 1:

Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

Example 2:

Input: strs = [""]
Output: [[""]]

Example 3:

Input: strs = ["a"]
Output: [["a"]]



  • 1 <= strs.length <= 104
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lower-case English letters.

Rust Solution

struct Solution;

use std::collections::HashMap;

impl Solution {
    fn group_anagrams(strs: Vec<String>) -> Vec<Vec<String>> {
        let mut group_hm: HashMap<Vec<char>, Vec<String>> = HashMap::new();
        for s in strs {
            let mut v: Vec<char> = s.chars().collect();
            let group = group_hm.entry(v).or_default();
        let mut res: Vec<Vec<String>> = vec![];
        for (_, mut v) in group_hm {
        res.sort_by_key(|x| x.len());

fn test() {
    let strs = vec_string!["eat", "tea", "tan", "ate", "nat", "bat"];
    let res = vec_vec_string![["bat"], ["nat", "tan"], ["ate", "eat", "tea"]];
    assert_eq!(Solution::group_anagrams(strs), res);

Having problems with this solution? Click here to submit an issue on github.