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 JavaScript

1 Answer

0 votes
/*
    Efficient algorithm using JavaScript Sets:
    -----------------------------------------
    Each word is converted into a Set 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 JavaScript's built-in:
        - Set()
        - for...of iteration
        - functional decomposition
*/


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


// Compute letters common to all words
function commonLetters(words) {
    if (words.length === 0) return new Set();

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

    // Intersect with each subsequent word
    for (let i = 1; i < words.length; i++) {
        const current = lettersOf(words[i]);
        common = new Set([...common].filter(ch => current.has(ch)));
    }

    return common;
}


// Print letters in sorted order
function printLetters(letters) {
    console.log([...letters].sort().join(" "));
}


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

const result = 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

...