Talentd
FleetCode
Make and follow sheets.Sign in

Maximum Number of Words You Can Type solution and explanation

EasyHash TableString5 min read82.9% acceptanceUpdated 9 Apr 2026
Maximum Number of Words You Can Type | Simple Approach | Leetcode 1935 | codestorywithMIKcodestorywithMIK · 8:38 · 4K viewsWatch on YouTube
9 more videos on this problem
  1. Maximum Number of Words You Can Type | Simple Approach | Leetcode 1935 | codestorywithMIKcodestorywithMIK · 8:38 · 4K views
  2. 1935. Maximum Number of Words You Can Type (Leetcode Easy)Programming Live with Larry · 2:59 · 637 views
  3. Leetcode 1935 Maximum Number of Words You Can Type - Java Clean Solution Using indexOf()AlgorithmicIQ · 8:28 · 441 views
  4. 1935. Maximum Number of Words You Can Type | Leetcode Daily - PythonLeetcode Daily · 6:28 · 413 views
  5. Maximum Words You Can Type | LeetCode 1935 | Sanyam IIT GuwahatiSanyam IIT Guwahati · 8:52 · 392 views
  6. Maximum Number of Words You Can Type | LeetCode 1935 | Java Code | Developer CoderDeveloper Coder · 5:25 · 343 views
  7. Daily Leetcode #1994: Sep 15, 2025 - 1935. Maximum Number of Words You Can TypeProgramming Live with Larry · 5:17 · 303 views
  8. 1935. Maximum Number of Words You Can Type || In JAVA || Easy Way #leetcodeQuick Learning With Sree · 8:37 · 258 views
  9. Maximum Number of Words You Can Type | LeetCode 1935 | Hash Table | String | Easy | Asked in QuoraCode Harmony · 11:57 · 222 views
  10. LeetCode 1935 🔥 Maximum Number of Words You Can Type | Daily Challenge | Java Solution + Dry Run Study Placement · 7:44 · 201 views

The 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.

Example 1:

Input: text = "hello world", brokenLetters = "ad"
Output: 1
Explanation: We cannot type "world" because the 'd' key is broken.

Example 2:

Input: text = "leet code", brokenLetters = "lt"
Output: 1
Explanation: We cannot type "leet" because the 'l' and 't' keys are broken.

Example 3:

Input: text = "leet code", brokenLetters = "e"
Output: 0
Explanation: We cannot type either word because the 'e' key is broken.

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 only consists of lowercase English letters.
  • brokenLetters consists of distinct lowercase English letters.

Approach overview

Problem Overview: You are given a sentence and a string representing broken keyboard letters. A word can be typed only if none of its characters appear in the broken set. The task is to count how many words in the sentence are fully typeable.

Approach 1: Checking Each Word for Broken Letters (O(n * m) time, O(b) space)

Split the sentence into individual words, then examine each word character by character. Store the broken letters in a hash set so every lookup runs in constant time. For every word, iterate through its characters and check whether any character exists in the broken set. If you encounter a broken letter, mark the word as invalid and move to the next one. This approach is straightforward and efficient because membership checks in a hash table are O(1). The overall runtime becomes O(n * m), where n is the number of words and m is the average word length.

Approach 2: Set Intersection to Determine Typeable Words (O(n * m) time, O(m + b) space)

Instead of scanning characters manually, convert each word into a character set and compute the intersection with the broken letters set. If the intersection is empty, the word is typeable. This approach relies heavily on built-in set operations in languages like Python or JavaScript, which are implemented efficiently in native code. The complexity remains O(n * m) because each word still requires processing all its characters, but the implementation is often shorter and easier to read.

Both methods rely on fast membership checks using a hash table or set structure. Since the input is primarily text processing, efficient iteration over characters in a string is the main operation. The difference is mostly stylistic: explicit iteration versus set operations.

Recommended for interviews: Approach 1 is usually preferred. It demonstrates clear control over iteration and hash lookups, which interviewers expect when testing basic string processing and set membership. Approach 2 is concise and elegant but relies more on language-specific conveniences. Showing the direct character-checking solution proves you understand the underlying logic rather than just using built-in set operations.

Approach 1: Approach 1: Checking Each Word for Broken Letters

In this approach, we will iterate over each word in the text and check if any of its characters are in the brokenLetters string. If a word does not contain any broken letters, it will be considered typeable, and we increment our count. This approach leverages the distinct nature of broken letters, allowing us to efficiently check inclusion using a set data structure.

def can_be_typed_words(text, broken_letters):
    broken = set(broken_letters)
    words = text.split()
    count = 0
    for word in words:
        if not set(word) & broken:
            count += 1
    return count

print(can_be_typed_words("hello world", "ad"))  # Output: 1
import java.util.*;

public class Solution {
    public int canBeTypedWords(String text, String brokenLetters) {
        Set<Character> broken = new HashSet<>();
        for (char c : brokenLetters.toCharArray()) {
            broken.add(c);
        }
        String[] words = text.split(" ");
        int count = 0;
        for (String word : words) {
            boolean isBroken = false;
            for (char c : word.toCharArray()) {
                if (broken.contains(c)) {
                    isBroken = true;
                    break;
                }
            }
            if (!isBroken) {
                count++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.canBeTypedWords("hello world", "ad")); // Output: 1
    }
}
#include <iostream>
#include <unordered_set>
#include <sstream>
using namespace std;

int canBeTypedWords(string text, string brokenLetters) {
    unordered_set<char> broken(brokenLetters.begin(), brokenLetters.end());
    stringstream ss(text);
    string word;
    int count = 0;
    while (ss >> word) {
        bool isBroken = false;
        for (char ch : word) {
            if (broken.count(ch)) {
                isBroken = true;
                break;
            }
        }
        if (!isBroken) {
            count++;
        }
    }
    return count;
}

int main() {
    cout << canBeTypedWords("hello world", "ad") << endl; // Output: 1
    return 0;
}
function canBeTypedWords(text, brokenLetters) {
    const broken = new Set(brokenLetters);
    const words = text.split(' ');
    let count = 0;
    for (const word of words) {
        if (![...word].some(ch => broken.has(ch))) {
            count++;
        }
    }
    return count;
}

console.log(canBeTypedWords("hello world", "ad")); // Output: 1
#include <stdio.h>
#include <string.h>
#include <stdbool.h>

int canBeTypedWords(char * text, char * brokenLetters) {
    int count = 0;
    bool isBroken;
    char *word = strtok(text, " ");
    
    while (word != NULL) {
        isBroken = false;
        for (int i = 0; i < strlen(word); i++) {
            if (strchr(brokenLetters, word[i]) != NULL) {
                isBroken = true;
                break;
            }
        }
        if (!isBroken) {
            count++;
        }
        word = strtok(NULL, " ");
    }
    return count;
}

int main() {
    char text[] = "hello world";
    char brokenLetters[] = "ad";
    printf("%d\n", canBeTypedWords(text, brokenLetters)); // Output: 1
    return 0;
}
using System;
using System.Collections.Generic;

public class Solution {
    public int CanBeTypedWords(string text, string brokenLetters) {
        HashSet<char> broken = new HashSet<char>(brokenLetters);
        string[] words = text.Split(' ');
        int count = 0;
        foreach (string word in words) {
            bool isBroken = false;
            foreach (char ch in word) {
                if (broken.Contains(ch)) {
                    isBroken = true;
                    break;
                }
            }
            if (!isBroken) count++;
        }
        return count;
    }

    public static void Main(string[] args) {
        Solution solution = new Solution();
        Console.WriteLine(solution.CanBeTypedWords("hello world", "ad")); // Output: 1
    }
}

In Python, the solution uses a set to store broken letters and leverages set intersection to check for common elements between the word and broken letters efficiently.

Complexity

Time Complexity: O(n + m), where n is the total number of characters in the text, and m is the number of broken letters. Space Complexity: O(m) for storing broken letters.

Try this approach in the editor

Approach 2: Approach 2: Set Intersection to Determine Typeable Words

This approach relies on using set operations to determine each word's typeability efficiently. By converting the text and broken letters into sets, we can directly determine if a word includes any broken letters using intersection operations.

def can_be_typed_words(text, broken_letters):
    broken = set(broken_letters)
    words = text.split()
    return sum(1 for word in words if not set(word) & broken)

print(can_be_typed_words("hello world", "ad"))  # Output: 1
function canBeTypedWords(text, brokenLetters) {
    const broken = new Set(brokenLetters);
    const words = text.split(' ');
    let count = 0;
    words.forEach(word => {
        const wordSet = new Set(word);
        if (![...broken].some(brokenChar => wordSet.has(brokenChar))) {
            count += 1;
        }
    });
    return count;
}

console.log(canBeTypedWords("hello world", "ad")); // Output: 1

Python's set capabilities allow us to efficiently determine if any of the broken letters appear in each word by using the intersection operator `&`. If the intersection is empty, the word can be typed.

Complexity

Time Complexity: O(n + m), where n is the total number of characters in the text, and m is the number of broken letters. Space Complexity: O(m) for storing broken letters as a set.

Try this approach in the editor

Approach 3: Array or Hash Table

We can use a hash table or an array s of length 26 to record all the broken letter keys.

Then, we traverse each word w in the string text, and if any letter c in w appears in s, it means that the word cannot be typed, and we do not need to add one to the answer. Otherwise, we need to add one to the answer.

After the traversal, we return the answer.

The time complexity is O(n), and the space complexity is O(|\Sigma|), where n is the length of the string text, and |\Sigma| is the size of the alphabet. In this problem, |\Sigma|=26.

function canBeTypedWords(text: string, brokenLetters: string): number {
    const s: boolean[] = Array(26).fill(false);
    for (const c of brokenLetters) {
        s[c.charCodeAt(0) - 'a'.charCodeAt(0)] = true;
    }
    let ans = 0;
    for (const w of text.split(' ')) {
        for (const c of w) {
            if (s[c.charCodeAt(0) - 'a'.charCodeAt(0)]) {
                --ans;
                break;
            }
        }
        ++ans;
    }
    return ans;
}
func canBeTypedWords(text string, brokenLetters string) (ans int) {
	s := [26]bool{}
	for _, c := range brokenLetters {
		s[c-'a'] = true
	}
	for _, w := range strings.Split(text, " ") {
		for _, c := range w {
			if s[c-'a'] {
				ans--
				break
			}
		}
		ans++
	}
	return
}
impl Solution {
    pub fn can_be_typed_words(text: String, broken_letters: String) -> i32 {
        let mut s = vec![false; 26];
        for c in broken_letters.chars() {
            s[(c as usize) - ('a' as usize)] = true;
        }
        let mut ans = 0;
        let words = text.split_whitespace();
        for w in words {
            for c in w.chars() {
                if s[(c as usize) - ('a' as usize)] {
                    ans -= 1;
                    break;
                }
            }
            ans += 1;
        }
        ans
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Approach 1: Checking Each Word for Broken Letters

Time Complexity: O(n + m), where n is the total number of characters in the text, and m is the number of broken letters. Space Complexity: O(m) for storing broken letters.

Approach 2: Set Intersection to Determine Typeable Words

Time Complexity: O(n + m), where n is the total number of characters in the text, and m is the number of broken letters. Space Complexity: O(m) for storing broken letters as a set.

Array or Hash Table–

Complexity analysis

ApproachTimeSpaceWhen to Use
Checking Each Word for Broken LettersO(n * m)O(b)General case. Clear logic using hash set lookups and character iteration.
Set Intersection Between Word and Broken LettersO(n * m)O(m + b)When using languages with efficient built-in set operations like Python or JavaScript.

Frequently asked questions

Is Maximum Number of Words You Can Type easy or hard?

Maximum Number of Words You Can Type is classified as an Easy problem. It focuses on basic string splitting, iteration, and hash set lookups. The challenge mainly tests careful character checking and understanding of constant-time set membership.

How to solve Maximum Number of Words You Can Type in O(n)?

Treat the sentence as n total characters and check each character only once while scanning words. Store broken letters in a hash set and verify that none appear in the current word. Each lookup is O(1), so the algorithm effectively processes the input string in linear time relative to its total length.

Maximum Number of Words You Can Type Python or Java solution

In Python, convert brokenLetters into a set and check each character of every word using membership tests. In Java, use a HashSet<Character> and iterate through the characters of each word. Both implementations follow the same O(n * m) time complexity pattern with constant-time lookups.

What is the best approach for Maximum Number of Words You Can Type?

The most practical approach stores all broken letters in a hash set and checks each word character by character. For every word, scan its letters and stop immediately if a broken character appears. This runs in O(n * m) time where n is the number of words and m is the average word length, with O(b) space for the broken letters.

What data structure is used in Maximum Number of Words You Can Type?

The key data structure is a hash set that stores the broken letters. It allows constant-time membership checks when scanning characters in each word. This makes it efficient to determine whether a word contains any invalid characters.

What is the time complexity of Maximum Number of Words You Can Type?

The typical solution runs in O(n * m) time. You split the sentence into n words and scan up to m characters per word while checking membership in a hash set. Space complexity is O(b), where b is the number of broken letters stored in the set.

Is Maximum Number of Words You Can Type asked at Google, Amazon, or Meta?

This problem represents a typical easy-level string and hash set question used in coding interviews. Variations of character filtering and word validation appear in interviews at companies like Amazon and Google, especially during early screening rounds focused on string manipulation.

Comments

Now write it yourselfClose this page and solve Maximum Number of Words You Can Type in the editor, without looking.
Practise Maximum Number of Words You Can Type