Maximum Number of Words You Can Type - Problem

There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly.

Given a string text of words separated by a single space (no leading or trailing spaces) and a string brokenLetters of all distinct letter keys that are broken, return the number of words in text you can fully type using this keyboard.

Input & Output

Example 1 — Basic Case
$ Input: text = "hello world", brokenLetters = "ad"
Output: 1
💡 Note: We can type "hello" (no 'a' or 'd'), but cannot type "world" (contains 'd'). So 1 word can be typed.
Example 2 — Multiple Broken Letters
$ Input: text = "leet code", brokenLetters = "lt"
Output: 1
💡 Note: We cannot type "leet" (contains 'l' and 't'), but can type "code" (no 'l' or 't'). So 1 word can be typed.
Example 3 — No Broken Letters
$ Input: text = "leet code", brokenLetters = ""
Output: 2
💡 Note: No keys are broken, so we can type all words: "leet" and "code". So 2 words can be typed.

Constraints

  • 1 ≤ text.length ≤ 104
  • 0 ≤ brokenLetters.length ≤ 26
  • text consists of words separated by a single space without any leading or trailing spaces
  • Each word consists of only lowercase English letters
  • brokenLetters consists of distinct lowercase English letters

Visualization

Tap to expand
Maximum Number of Words You Can Type INPUT text = "hello world" hello world brokenLetters = "ad" Keyboard q w e r t y a s d f g h = Broken key Hash Set Created: {'a', 'd'} ALGORITHM STEPS 1 Build Hash Set Store broken letters in set O(1) lookup time 2 Split Text Separate words by space ["hello", "world"] 3 Check Each Word For each char, check set "hello": h-e-l-l-o OK (no broken) "world": w-o-r-l-d FAIL ('d' broken) d in set! 4 Count Valid Words Increment if all chars OK count = 1 FINAL RESULT Words Analysis: "hello" CAN TYPE No broken letters used "world" CANNOT Contains 'd' (broken) OUTPUT 1 1 word can be fully typed using the keyboard Key Insight: Hash Set Optimization Using a Hash Set for broken letters provides O(1) lookup time for each character check. Time Complexity: O(n + m) where n = total chars in text, m = broken letters count. Space Complexity: O(k) where k = number of broken letters (at most 26). TutorialsPoint - Maximum Number of Words You Can Type | Hash Set Optimization Approach
Asked in
Amazon 15 Microsoft 8
12.5K Views
Medium Frequency
~10 min Avg. Time
420 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