#1160
Find Words That Can Be Formed by Characters
EasyArrayHash TableStringCountingHash 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 solution uses a frequency count of characters in both the chars string and each word. This allows us to quickly determine if a word can be formed by comparing counts, which is more efficient than checking character by character.
⚙️
Algorithm
6 steps- 1Step 1: Create a frequency map (dictionary) for characters in chars.
- 2Step 2: Initialize a variable to keep track of the total length of good words.
- 3Step 3: For each word in the words array, create a frequency map for that word.
- 4Step 4: Compare the frequency of each character in the word with the frequency in chars.
- 5Step 5: If all characters in the word can be formed, add the length of the word to the total.
- 6Step 6: Return the total length of all good words.
solution.py11 lines
1# Full working Python code
2
3def countCharacters(words, chars):
4 from collections import Counter
5 char_count = Counter(chars)
6 total_length = 0
7 for word in words:
8 word_count = Counter(word)
9 if all(word_count[c] <= char_count[c] for c in word_count):
10 total_length += len(word)
11 return total_lengthℹ
Complexity note: The time complexity is O(n) because we traverse each word and chars string once to build frequency maps. The space complexity is O(n) due to the storage of these frequency maps.
- 1Using frequency counts allows for faster checks compared to character-by-character matching.
- 2Understanding the constraints of the problem helps in designing efficient algorithms.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.