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

1 Answer

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

    Example:
        "algebraic" -> setOf('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 Kotlin's built-in:
        - Set<Char>
        - intersect()
        - map, drop, and functional decomposition
*/


// Convert a word into a Set<Char> of its unique letters
fun lettersOf(word: String): Set<Char> =
    word.toSet()


// Compute letters common to all words
fun commonLetters(words: List<String>): Set<Char> {
    if (words.isEmpty()) return emptySet()

    // Start with letters of the first word
    var common: Set<Char> = lettersOf(words.first())

    // Intersect with each subsequent word
    for (word in words.drop(1)) {
        val current: Set<Char> = lettersOf(word)
        common = common.intersect(current)
    }

    return common
}


// Print letters in sorted order
fun printLetters(letters: Set<Char>) {
    println(letters.sorted().joinToString(" "))
}


fun main() {
    val words: List<String> = listOf(
        "algebraic",
        "alphabetic",
        "ambiance",
        "abacus",
        "metabolic",
        "parabolic",
        "playback",
        "drawback",
        "fabricate",
        "flashback",
        "syllabic"
    )

    val result: Set<Char> = commonLetters(words)

    println("Common letters across all words:")
    printLetters(result)
}


/*
run:

Common letters across all words:
a b c

*/

 



answered 3 hours ago by avibootz

Related questions

...