#1935
Maximum Number of Words You Can Type
EasyHash TableStringHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a HashSet to store broken letters for O(1) lookup time. This allows us to efficiently check each word against the broken letters without nested loops.
⚙️
Algorithm
5 steps- 1Step 1: Convert brokenLetters into a HashSet for fast lookups.
- 2Step 2: Split the text into individual words.
- 3Step 3: For each word, check if it contains any letter from the HashSet of broken letters.
- 4Step 4: If a word can be fully typed, increment a count.
- 5Step 5: Return the count of words that can be fully typed.
solution.py10 lines
1# Full working Python code
2
3def canType(text, brokenLetters):
4 broken_set = set(brokenLetters)
5 words = text.split()
6 count = 0
7 for word in words:
8 if not any(char in broken_set for char in word):
9 count += 1
10 return countℹ
Complexity note: The time complexity is O(n) because we only traverse the text and check each character against the HashSet. The space complexity is O(n) due to the storage of broken letters in the HashSet.
- 1Using a HashSet allows for O(1) average time complexity for lookups.
- 2Checking each word independently is crucial for counting correctly.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.