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

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <algorithm>

/*
    This program finds the letters that appear in *every* word
    from a given list. It uses idiomatic C++ and STL algorithms.

    We break the logic into clean, reusable functions:
    1. letters_of(word) → returns a set<char> of unique letters
    2. intersect_sets(a, b) → returns intersection of two sets
    3. common_letters(words) → returns letters common to all words
*/


// Convert a word into a set of its unique characters
std::set<char> letters_of(const std::string& word) {
    return std::set<char>(word.begin(), word.end());
}


// Compute intersection of two sets using std::set_intersection
std::set<char> intersect_sets(const std::set<char>& a,
                              const std::set<char>& b) {
    std::set<char> result;

    std::set_intersection(
        a.begin(), a.end(),
        b.begin(), b.end(),
        std::inserter(result, result.begin())
    );

    return result;
}


// Compute letters common to all words in the list
std::set<char> common_letters(const std::vector<std::string>& words) {
    if (words.empty()) return {};

    // Start with letters of the first word
    std::set<char> common = letters_of(words[0]);

    // Intersect with each subsequent word
    for (size_t i = 1; i < words.size(); ++i) {
        std::set<char> current = letters_of(words[i]);
        common = intersect_sets(common, current);
    }

    return common;
}


int main() {
    std::vector<std::string> words = {
        "algebraic",
        "alphabetic",
        "ambiance",
        "abacus",
        "metabolic",
        "parabolic",
        "playback",
        "drawback",
        "fabricate",
        "flashback",
        "syllabic"
    };

    std::set<char> result = common_letters(words);

    std::cout << "Common letters across all words:\n";
    for (char c : result) {
        std::cout << c << " ";
    }
}



/*
run:

Common letters across all words:
a b c 

*/


 



answered 4 hours ago by avibootz
...