#2135
Count Words Obtained After Adding a Letter
MediumArrayHash TableStringBit ManipulationSortingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n + m log m) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n + m log m)Space O(n)
The optimal solution uses a set to store the sorted versions of start words, allowing for quick checks against target words. By focusing on the sorted version, we can easily see if a target can be formed by adding a letter to a start word.
⚙️
Algorithm
3 steps- 1Step 1: Create a set to store the sorted versions of all start words.
- 2Step 2: For each target word, sort it and check if the sorted version minus one character exists in the set.
- 3Step 3: Count how many target words can be formed and return this count.
solution.py10 lines
1def countWords(startWords, targetWords):
2 start_set = set(''.join(sorted(word)) for word in startWords)
3 count = 0
4 for target in targetWords:
5 sorted_target = ''.join(sorted(target))
6 for c in 'abcdefghijklmnopqrstuvwxyz':
7 if sorted_target[:-1] in start_set:
8 count += 1
9 break
10 return countℹ
Complexity note: The complexity arises from sorting the words in both startWords and targetWords, which is O(n log n) for startWords and O(m log m) for targetWords, where n and m are their respective lengths.
- 1Sorting helps in quickly identifying if a target can be formed from a start word.
- 2Using a set allows for O(1) average time complexity checks for existence.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.