Longest String Chain - Problem
You are given an array of words where each word consists of lowercase English letters. Your task is to find the longest possible word chain that can be formed from these words.
What is a Word Chain?
A word chain is a sequence of words where each word is a predecessor of the next word. Word A is a predecessor of word B if and only if we can insert exactly one letter anywhere in word A (without changing the order of other characters) to make it equal to word B.
Examples of predecessors:
"abc"is a predecessor of"abxc"(insert 'x' at position 2)"abc"is a predecessor of"xabc"(insert 'x' at position 0)"cba"is NOT a predecessor of"bcad"(would require reordering)
Goal: Return the length of the longest possible word chain. A single word is trivially a word chain of length 1.
Input & Output
example_1.py โ Basic Chain
$
Input:
["a","b","ba","bca","bda","bdca"]
โบ
Output:
4
๐ก Note:
One of the longest word chains is ["a","ba","bda","bdca"] with length 4. Another valid chain is ["a","ba","bca","bdca"].
example_2.py โ Multiple Chains
$
Input:
["xbc","pcxbcf","xb","cxbc","pcxbc"]
โบ
Output:
5
๐ก Note:
The longest chain is ["xb","xbc","cxbc","pcxbc","pcxbcf"] with length 5.
example_3.py โ Single Word
$
Input:
["abde","abc","abd","abcde","ade","ae","1abde","1abc","1abd","1abcde","1ade","1ae"]
โบ
Output:
4
๐ก Note:
Multiple chains of length 4 exist, such as ["ae","ade","abde","abcde"].
Constraints
- 1 โค words.length โค 1000
- 1 โค words[i].length โค 16
- words[i] only contains lowercase English letters
- All strings are unique
Visualization
Tap to expand
Understanding the Visualization
1
Sort by Complexity
Arrange words by length - simpler forms must come before complex ones
2
Build Incrementally
For each word, check if removing any character gives us a known predecessor
3
Track Best Path
Remember the longest chain ending at each word using memoization
4
Find Maximum
Return the length of the longest chain found
Key Takeaway
๐ฏ Key Insight: By processing words in length order and using dynamic programming, we ensure that when we process a word of length n, all its potential predecessors of length n-1 have already been processed and their optimal chain lengths are known.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code