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 C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <stdint.h>

/*
    Efficient algorithm:
    --------------------
    Represent letters using a 32-bit bitmask:
        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 dynamic memory, sorting, and repeated scanning.
*/


/* Convert a word into a bitmask of its letters */
uint32_t word_to_mask(const char *word) {
    uint32_t mask = 0;
    for (size_t i = 0; word[i] != '\0'; i++) {
        char c = word[i];
        if (c >= 'a' && c <= 'z') {
            mask |= (1u << (c - 'a'));   // set bit for this letter
        }
    }
    return mask;
}

/* Compute common letters across all words */
uint32_t common_letters(const char *words[], size_t count) {
    if (count == 0) return 0;

    uint32_t common = word_to_mask(words[0]);

    for (size_t i = 1; i < count; i++) {
        uint32_t current = word_to_mask(words[i]);
        common &= current;   // bitwise intersection
    }

    return common;
}

/* Print letters represented by a bitmask */
void print_mask_letters(uint32_t mask) {
    for (int i = 0; i < 26; i++) {
        if (mask & (1u << i)) {
            printf("%c ", 'a' + i);
        }
    }
    printf("\n");
}

int main(void) {
    const char *words[] = {
        "algebraic",
        "alphabetic",
        "ambiance",
        "abacus",
        "metabolic",
        "parabolic",
        "playback",
        "drawback",
        "fabricate",
        "flashback",
        "syllabic"
    };

    size_t count = sizeof(words) / sizeof(words[0]);

    uint32_t result = common_letters(words, count);

    printf("Common letters across all words:\n");
    print_mask_letters(result);

    return 0;
}


/*
run:

Common letters across all words:
a b c 

*/

 



answered Jul 10 by avibootz

Related questions

...