Maximum Number of Words You Can Type - Complete Solution Guide
Maximum Number of Words You Can Type is LeetCode problem 1935, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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 . Example 1: Input: text = "hello world", brokenLetters = "ad" Output: 1 Explanation: We cannot type "world" because the 'd' key is broken. Example
Detailed Explanation
The problem asks you to count the number of words from a given string that can be typed using a malfunctioning keyboard. The input consists of two strings: `text`, containing words separated by spaces, and `brokenLetters`, containing the characters of broken keys. The output is the number of words from `text` that can be typed without using any broken keys. The problem assumes all letters are lowercase and that `brokenLetters` contains only distinct characters.
Solution Approach
The provided solutions all follow a similar approach. They first split the input `text` string into individual words. Then, they iterate through each word and check if it contains any character from the `brokenLetters` string. If a broken character is found, the word is considered untypeable. Otherwise, a counter is incremented. Finally, the counter (representing the number of typeable words) is returned.
Step-by-Step Algorithm
- Step 1: Split the input string `text` into an array of words (using `text.split()` in Python, `text.split(" ")` in Java, `stringstream` in C++, or manual iteration in C).
- Step 2: Iterate through each word in the array.
- Step 3: For each word, iterate through the characters of `brokenLetters`.
- Step 4: If a character from `brokenLetters` is found in the current word, set a flag (`canType`) to `false` and break the inner loop.
- Step 5: If the flag (`canType`) is still `true` after checking all characters in `brokenLetters`, increment the `count` of typeable words.
- Step 6: After processing all words, return the final `count`.
Key Insights
- Insight 1: The problem can be solved by iterating through each word in the `text` string and checking if any character in the word is present in the `brokenLetters` string.
- Insight 2: A simple boolean flag (`canType` in the provided solutions) can efficiently track whether a word contains a broken letter.
- Insight 3: String splitting is a crucial preprocessing step to efficiently handle each word individually.
Complexity Analysis
Time Complexity: O(n*m)
Space Complexity: O(n)
Topics
This problem involves: Hash Table, String.
Companies
Asked at: Quora.