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,656 questions

55,396 answers

573 users

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

1 Answer

0 votes
/*
    Efficient algorithm using TypeScript Sets:
    -----------------------------------------
    Each word is converted into a Set<string> of its unique letters.

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

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

    This uses TypeScript's built-in:
        - Set<string>
        - for...of iteration
        - array slicing
        - functional decomposition
*/


// Convert a word into a Set<string> of its unique letters
function lettersOf(word: string): Set<string> {
    return new Set<string>(word);
}


// Compute letters common to all words
function commonLetters(words: string[]): Set<string> {
    if (words.length === 0) {
        return new Set<string>();
    }

    // Start with letters of the first word
    let common: Set<string> = lettersOf(words[0]);

    // Intersect with each subsequent word
    for (const word of words.slice(1)) {
        const current: Set<string> = lettersOf(word);

        // Filter only letters that appear in both sets
        const intersection: Set<string> =
            new Set<string>([...common].filter((ch: string) => current.has(ch)));

        common = intersection;
    }

    return common;
}


// Print letters in sorted order
function printLetters(letters: Set<string>): void {
    const sorted: string[] = [...letters].sort();
    console.log(sorted.join(" "));
}


// Main program
const words: string[] = [
    "algebraic",
    "alphabetic",
    "ambiance",
    "abacus",
    "metabolic",
    "parabolic",
    "playback",
    "drawback",
    "fabricate",
    "flashback",
    "syllabic"
];

const result: Set<string> = commonLetters(words);

console.log("Common letters across all words:");
printLetters(result);



/*
run:

Common letters across all words:
a b c

*/

 



answered Jul 10 by avibootz

Related questions

...