Count Words Obtained After Adding a Letter - Problem
Word Transformation Challenge: You have two collections of words - a starting set and a target set. Your mission is to determine how many target words can be created by transforming words from the starting set.
The transformation rules are:
1. Add exactly one letter that doesn't already exist in the word
2. Rearrange all letters in any order you want
For example:
Goal: Count how many words in
The transformation rules are:
1. Add exactly one letter that doesn't already exist in the word
2. Rearrange all letters in any order you want
For example:
"abc" can become "dabc" (add 'd'), then rearrange to "bdac", "cadb", etc.Goal: Count how many words in
targetWords can be obtained by transforming any word from startWords. Input & Output
example_1.py โ Basic Transformation
$
Input:
startWords = ["ant","act","tack"], targetWords = ["tack","act","acti"]
โบ
Output:
2
๐ก Note:
- "tack": Can be formed from "act" by adding 'k' then rearranging to "tack"
- "act": Cannot be formed (would need to remove a letter, not add)
- "acti": Can be formed from "act" by adding 'i' then rearranging to "acti"
example_2.py โ No Valid Transformations
$
Input:
startWords = ["ab","a"], targetWords = ["abc","abcd"]
โบ
Output:
1
๐ก Note:
- "abc": Can be formed from "ab" by adding 'c'
- "abcd": Cannot be formed ("ab" + any letter gives max 3 letters, but "abcd" has 4)
example_3.py โ Edge Case with Duplicates
$
Input:
startWords = ["a","aa"], targetWords = ["ab"]
โบ
Output:
1
๐ก Note:
- "ab": Can be formed from "a" by adding 'b'. Note that "aa" cannot form "ab" because adding any letter to "aa" would give a word with 2 'a's, but "ab" has only 1 'a'.
Visualization
Tap to expand
Understanding the Visualization
1
Encode Recipes
Convert each start word to a bitmask representing its character set
2
Analyze Orders
For each target word, systematically try removing each character
3
Quick Match
Check if the resulting character set matches any start word
4
Count Success
Increment counter for each successful transformation found
Key Takeaway
๐ฏ Key Insight: Since we can rearrange letters freely, only the SET of characters matters, not their order. Bitmasks give us ultra-fast set operations!
Time & Space Complexity
Time Complexity
O(m*26 + n*k)
m=targetWords, 26 letters to try removing, n=startWords, k=average word length for bitmask creation
โ Linear Growth
Space Complexity
O(n)
Store bitmask for each start word in HashSet
โก Linearithmic Space
Constraints
- 1 โค startWords.length, targetWords.length โค 5 ร 104
- 1 โค startWords[i].length, targetWords[i].length โค 26
- startWords[i] and targetWords[i] consist of lowercase English letters only
- All strings in startWords are unique
- All strings in targetWords are unique
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code