Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
A word is typeable exactly when none of its characters uses a broken key. Words are independent, and a single broken character is enough to reject a word immediately.
Approach
Split the text into its space-separated words and store the broken letters in a set. For each word, test its characters for membership in that set; skip the word on the first match and count it otherwise. Return the number of accepted words. Repeated occurrences of a word count separately because the task counts words in the text, not distinct spellings. With no broken letters, every word passes.
class Solution:
def canBeTypedWords(self, text: str, brokenLetters: str) -> int:
text = text.split(' ')
brokenLetters = set(brokenLetters)
res = 0
for w in text:
if any(c in brokenLetters for c in w):
continue
res += 1
return resComplexity analysis
Let c be the total characters in text and b = brokenLetters.length. Time: O(c + b). Auxiliary space: O(c + b) for the split words and broken-letter set.
