How to convert an array of strings and group all the anagrams into subarrays in Rust

1 Answer

0 votes
use std::collections::HashMap;

fn group_anagrams(words: &[&str]) -> Vec<Vec<String>> {
    let mut map: HashMap<String, Vec<String>> = HashMap::new();

    for &word in words {
        // Sort the characters in the word to create a key
        let mut chars: Vec<char> = word.chars().collect();
        chars.sort_unstable();
        let key: String = chars.into_iter().collect();

        // Group words by their sorted key
        map.entry(key).or_default().push(word.to_string());
    }

    // Collect grouped anagrams into a vector of vectors
    map.into_values().collect()
}

fn main() {
    let arr = ["eat", "tea", "rop", "ate", "nat", "orp", "tan", "bat", "pro"];
    let result = group_anagrams(&arr);

    println!("Grouped anagrams:");
    for group in result {
        println!("{:?}", group);
    }
}




/*
run:

Grouped anagrams:
["bat"]
["eat", "tea", "ate"]
["rop", "orp", "pro"]
["nat", "tan"]

*/

 



answered Nov 15, 2025 by avibootz
...