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

1 Answer

0 votes
using System;
using System.Collections.Generic;

/*
    Efficient algorithm using bitmasking:
    ------------------------------------
    Each letter 'a'..'z' is represented by one bit in a 32-bit int.

        bit 0  -> 'a'
        bit 1  -> 'b'
        ...
        bit 25 -> 'z'

    For each word:
        - Set the bit corresponding to each letter.
    Then:
        - Intersect all bitmasks using bitwise AND.
    The remaining bits represent letters common to all words.

    This avoids sorting, dynamic memory, and repeated scanning.
*/

class CommonLettersProgram
{
    // Convert a word into a bitmask of its letters
    static int WordToMask(string word)
    {
        int mask = 0;

        foreach (char c in word) {
            if (c >= 'a' && c <= 'z') {
                mask |= (1 << (c - 'a'));   // set bit for this letter
            }
        }

        return mask;
    }

    // Compute common letters across all words
    static int CommonLetters(List<string> words)
    {
        if (words.Count == 0) return 0;

        int common = WordToMask(words[0]);

        for (int i = 1; i < words.Count; i++) {
            common &= WordToMask(words[i]);   // bitwise intersection
        }

        return common;
    }

    // Print letters represented by a bitmask
    static void PrintMaskLetters(int mask)
    {
        for (int i = 0; i < 26; i++) {
            if ((mask & (1 << i)) != 0) {
                Console.Write((char)('a' + i) + " ");
            }
        }
        Console.WriteLine();
    }

    static void Main()
    {
        List<string> words = new List<string>
        {
            "algebraic",
            "alphabetic",
            "ambiance",
            "abacus",
            "metabolic",
            "parabolic",
            "playback",
            "drawback",
            "fabricate",
            "flashback",
            "syllabic"
        };

        int result = CommonLetters(words);

        Console.WriteLine("Common letters across all words:");
        PrintMaskLetters(result);
    }
}


/*
run:

Common letters across all words:
a b c

*/

 



answered 4 hours ago by avibootz
...