Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,623 questions

55,358 answers

573 users

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 Jul 10 by avibootz

Related questions

...