DDSA Solutions

1935. Maximum Number of Words You Can Type

Time: O(n*m)
Space: O(1)
Advertisement

Approach

Mark broken letters in a boolean array; count words with no broken letter.

Key Techniques

Hash Table

Hash tables provide O(1) average-case lookup, insert, and delete. They are the go-to tool for counting frequencies, detecting complements (Two Sum pattern), and caching seen values. In C#, use Dictionary<K,V> for maps and HashSet<T> for membership checks.

String

String problems range from simple character counting to complex pattern matching. Common approaches include two pointers, sliding window, prefix hashing, and the KMP algorithm. In C#, strings are immutable — use StringBuilder for efficient concatenation inside loops.

1935.cs
C#
// Approach: Mark broken letters in a boolean array; count words with no broken letter.
// Time: O(n*m) Space: O(1)

public class Solution
{
    public int CanBeTypedWords(string text, string brokenLetters)
    {
        // Create a boolean array to mark which letters are broken
        // Index represents letter position (0 for 'a', 1 for 'b', etc.)
        bool[] isBrokenLetter = new bool[26];

        // Mark all broken letters as true in the array
        foreach (char letter in brokenLetters)
            isBrokenLetter[letter - 'a'] = true;

        // Counter for words that can be typed
        int typableWordCount = 0;

        // Split the text into words and check each word
        foreach (string word in text.Split(' '))
        {
            // Assume the word can be typed initially
            bool canTypeWord = true;

            // Check each character in the current word
            foreach (char character in word)
            {
                // If any character is a broken letter, the word cannot be typed
                if (isBrokenLetter[character - 'a'])
                {
                    canTypeWord = false;
                    break;
                }
            }

            // Increment count if the word can be typed
            if (canTypeWord)
                typableWordCount++;
        }

        return typableWordCount;
    }
}
Advertisement
Was this solution helpful?