Maximum Number of Words You Can Type - Problem

Imagine you're working on an old computer with a faulty keyboard where some keys just won't respond when you press them! Your task is to determine how many complete words from a given text you can actually type.

You're given:

  • A text string containing words separated by single spaces (no leading or trailing spaces)
  • A brokenLetters string containing all the distinct letter keys that don't work

Your goal is to return the number of words in the text that you can fully type using this malfunctioning keyboard.

Example: If your text is "hello world" and the broken letters are "ad", you can type "hello" completely (no 'a' or 'd' needed), but you cannot type "world" because it contains the broken letter 'd'. So the answer would be 1.

Input & Output

example_1.py โ€” Basic Case
$ Input: text = "hello world", brokenLetters = "ad"
โ€บ Output: 1
๐Ÿ’ก Note: We can type "hello" completely since it doesn't contain 'a' or 'd'. However, "world" contains 'd' which is broken, so we can't type it. Total: 1 word.
example_2.py โ€” Multiple Broken Letters
$ Input: text = "leet code", brokenLetters = "lt"
โ€บ Output: 1
๐Ÿ’ก Note: "leet" contains both 'l' and 't' which are broken, so it cannot be typed. "code" doesn't contain 'l' or 't', so it can be typed. Total: 1 word.
example_3.py โ€” No Broken Letters
$ Input: text = "leet code", brokenLetters = ""
โ€บ Output: 2
๐Ÿ’ก Note: No letters are broken, so we can type all words: "leet" and "code". Total: 2 words.

Constraints

  • 1 โ‰ค text.length โ‰ค 104
  • 0 โ‰ค brokenLetters.length โ‰ค 26
  • text consists of words separated by single spaces, no leading or trailing spaces
  • Each word consists only of lowercase English letters
  • brokenLetters consists of distinct lowercase English letters

Visualization

Tap to expand
Broken Keyboard Word Counter VisualizationKeyboard StatusHELOAD...other keysโœ“ Workingโœ— BrokenWord: "HELLO"HELLOAll letters working!โœ“ CAN TYPEWord: "WORLD"WORLDContains broken letter 'D'!โœ— CANNOT TYPEFinal Result1 out of 2 words can be typed
Understanding the Visualization
1
Build Broken Keys Set
Create a fast lookup table of all the broken keyboard keys
2
Examine Each Word
Go through each word in the text one by one
3
Check Every Letter
For each word, verify that none of its letters are in the broken keys set
4
Count Typeable Words
Only count words that can be completely typed without any broken letters
Key Takeaway
๐ŸŽฏ Key Insight: Use a hash set to convert the broken letters into a fast O(1) lookup table, then check each word's letters against this set. This transforms an O(nร—mร—k) brute force solution into an optimal O(n+m) solution.
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 6
32.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen