The "Maximum Number of Words You Can Type" problem asks you to determine how many words in a given text
can be typed when certain keys on the keyboard are broken.
Specifically:
text
consisting of words separated by single spaces.brokenLetters
containing distinct lowercase English letters, each representing a broken key on the keyboard.text
do not contain any letter from brokenLetters
.text
is non-empty and separated by exactly one space.Before jumping into code, let's consider how to solve the problem efficiently:
brokenLetters
.Let's break down the steps for an efficient solution:
brokenLetters
into a set. This allows O(1) lookup for each character.
split
function to divide text
into a list/array of words.
Let's walk through an example step by step:
Input:
text = "hello world leetcode"
brokenLetters = "ad"
brokenLetters
to a set: {'a', 'd'}
text
into words: ["hello", "world", "leetcode"]
"hello"
: letters are h, e, l, l, o
. None are broken. Count = 1"world"
: letters are w, o, r, l, d
. d
is broken. Skip"leetcode"
: letters are l, e, e, t, c, o, d, e
. d
is broken. Skip"hello"
can be typed with the given broken keys.
Brute-force approach:
n
words), for each letter in the word (average length m
), for each broken letter (length b
): O(n * m * b)
O(b)
O(L)
where L
is the total length of textO(n * m)
with O(1) lookup per letterO(L + b)
(since every character is checked once)O(b)
for the set, plus space for the split wordsIn summary, the problem is solved efficiently by:
class Solution:
def canBeTypedWords(self, text: str, brokenLetters: str) -> int:
broken = set(brokenLetters)
count = 0
for word in text.split():
if all(ch not in broken for ch in word):
count += 1
return count
class Solution {
public:
int canBeTypedWords(string text, string brokenLetters) {
unordered_set<char> broken(brokenLetters.begin(), brokenLetters.end());
int count = 0;
istringstream iss(text);
string word;
while (iss >> word) {
bool canType = true;
for (char ch : word) {
if (broken.count(ch)) {
canType = false;
break;
}
}
if (canType) count++;
}
return count;
}
};
class Solution {
public int canBeTypedWords(String text, String brokenLetters) {
Set<Character> broken = new HashSet<>();
for (char ch : brokenLetters.toCharArray()) {
broken.add(ch);
}
int count = 0;
String[] words = text.split(" ");
for (String word : words) {
boolean canType = true;
for (char ch : word.toCharArray()) {
if (broken.contains(ch)) {
canType = false;
break;
}
}
if (canType) count++;
}
return count;
}
}
var canBeTypedWords = function(text, brokenLetters) {
const broken = new Set(brokenLetters);
let count = 0;
const words = text.split(' ');
for (const word of words) {
let canType = true;
for (const ch of word) {
if (broken.has(ch)) {
canType = false;
break;
}
}
if (canType) count++;
}
return count;
};