import Foundation
/*
Efficient algorithm using Swift Sets:
------------------------------------
Each word is converted into a Set<Character> 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 Swift's built-in:
- Set<Character>
- intersection()
- map, dropFirst(), and functional decomposition
*/
// Convert a word into a Set<Character> of its unique letters
func lettersOf(_ word: String) -> Set<Character> {
return Set(word)
}
// Compute letters common to all words
func commonLetters(_ words: [String]) -> Set<Character> {
guard let first = words.first else { return [] }
// Start with letters of the first word
var common: Set<Character> = lettersOf(first)
// Intersect with each subsequent word
for word in words.dropFirst() {
let current: Set<Character> = lettersOf(word)
common = common.intersection(current)
}
return common
}
// Print letters in sorted order
func printLetters(_ letters: Set<Character>) {
let sorted = letters.sorted()
print(sorted.map { String($0) }.joined(separator: " "))
}
// Main program
let words: [String] = [
"algebraic",
"alphabetic",
"ambiance",
"abacus",
"metabolic",
"parabolic",
"playback",
"drawback",
"fabricate",
"flashback",
"syllabic"
]
let result: Set<Character> = commonLetters(words)
print("Common letters across all words:")
printLetters(result)
/*
run:
Common letters across all words:
a b c
*/