How to get common letters that appear in every word in a list of words with Rust

1 Answer

0 votes
use std::collections::HashSet;

/*
    Efficient algorithm using Rust HashSet:
    ---------------------------------------
    Each word is converted into a HashSet<char> of its unique letters.

    Example:
        "algebraic" -> {'a', 'l', 'g', 'e', 'b', 'r', 'i', 'c'}

    Then:
        - Start with the letter-set of the first word.
        - Intersect with each subsequent word's letter-set.
        - The final set contains letters common to all words.

    This uses Rust's built-in:
        - HashSet<char>
        - retain() for efficient in-place intersection
        - iterators and functional decomposition
*/


// Convert a word into a set of its unique letters
fn letters_of(word: &str) -> HashSet<char> {
    word.chars().collect()
}


// Compute letters common to all words
fn common_letters(words: &[&str]) -> HashSet<char> {
    if words.is_empty() {
        return HashSet::new();
    }

    // Start with letters of the first word
    let mut common = letters_of(words[0]);

    // Intersect with each subsequent word
    for word in &words[1..] {
        let current = letters_of(word);

        // Retain only letters that appear in both sets
        common.retain(|ch| current.contains(ch));
    }

    common
}


// Print letters in sorted order
fn print_letters(letters: &HashSet<char>) {
    let mut list: Vec<char> = letters.iter().copied().collect();
    list.sort();
    for ch in list {
        print!("{} ", ch);
    }
    println!();
}


fn main() {
    let words = [
        "algebraic",
        "alphabetic",
        "ambiance",
        "abacus",
        "metabolic",
        "parabolic",
        "playback",
        "drawback",
        "fabricate",
        "flashback",
        "syllabic",
    ];

    let result = common_letters(&words);

    println!("Common letters across all words:");
    print_letters(&result);
}


/*
run:

Common letters across all words:
a b c

*/

 



answered 3 hours ago by avibootz

Related questions

...