/*
Efficient algorithm using TypeScript Sets:
-----------------------------------------
Each word is converted into a Set<string> 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 TypeScript's built-in:
- Set<string>
- for...of iteration
- array slicing
- functional decomposition
*/
// Convert a word into a Set<string> of its unique letters
function lettersOf(word: string): Set<string> {
return new Set<string>(word);
}
// Compute letters common to all words
function commonLetters(words: string[]): Set<string> {
if (words.length === 0) {
return new Set<string>();
}
// Start with letters of the first word
let common: Set<string> = lettersOf(words[0]);
// Intersect with each subsequent word
for (const word of words.slice(1)) {
const current: Set<string> = lettersOf(word);
// Filter only letters that appear in both sets
const intersection: Set<string> =
new Set<string>([...common].filter((ch: string) => current.has(ch)));
common = intersection;
}
return common;
}
// Print letters in sorted order
function printLetters(letters: Set<string>): void {
const sorted: string[] = [...letters].sort();
console.log(sorted.join(" "));
}
// Main program
const words: string[] = [
"algebraic",
"alphabetic",
"ambiance",
"abacus",
"metabolic",
"parabolic",
"playback",
"drawback",
"fabricate",
"flashback",
"syllabic"
];
const result: Set<string> = commonLetters(words);
console.log("Common letters across all words:");
printLetters(result);
/*
run:
Common letters across all words:
a b c
*/