/*
Efficient algorithm using Scala Sets:
-------------------------------------
Each word is converted into a Set[Char] 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 Scala's built-in:
- Set[Char]
- intersect (&)
- map, drop, and functional decomposition
*/
object CommonLettersApp {
// Convert a word into a Set[Char] of its unique letters
def lettersOf(word: String): Set[Char] =
word.toSet
// Compute letters common to all words
def commonLetters(words: List[String]): Set[Char] = {
if (words.isEmpty) return Set.empty
// Start with letters of the first word
var common: Set[Char] = lettersOf(words.head)
// Intersect with each subsequent word
for (word <- words.drop(1)) {
val current: Set[Char] = lettersOf(word)
common = common & current // Scala's built-in set intersection
}
common
}
// Print letters in sorted order
def printLetters(letters: Set[Char]): Unit = {
println(letters.toList.sorted.mkString(" "))
}
def main(args: Array[String]): Unit = {
val words: List[String] = List(
"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
*/