We are given the problem: "You are given a list of strings words. Write a function to find the longest string chain. A string chain is a sequence of words word1, word2, ..., wordk where each word is a predecessor of the next. A word is a predecessor if you can add exactly one letter anywhere in it to form the next word." We need to write a function that solves this and explain the DP approach. Sorting by length is important.
We need to produce a solution in code, likely Python. Let's outline the approach.
Problem: Given a list of words, find the length of the longest possible string chain. A string chain is a sequence where each word is formed by adding exactly one character to the previous word. That means if word A is a predecessor of word B, then len(A) + 1 = len(B) and there exists exactly one character that can be inserted into A (or removed from B) to get the other.
We are to return the maximum chain length.
Approach: Sort the words by length ascending. Then for each word, we can try to find if there exists a predecessor in the set of words that is one length shorter and can be formed by removing one character from the current word. Because if we have a word w of length L, then any predecessor must have length L-1 and be such that by removing one character from w we get that predecessor. So we can consider all possible removals of one character from w and check if that string exists in the set of words (or at least in the set of words we have processed, but since sorted by length, all shorter words are already processed). Then the chain length ending at w is 1 + max(chain length of all valid predecessors). If no predecessor, chain length is 1 (the word itself).
We use DP: dp[word] = longest chain ending at word. We can use a dictionary mapping word to its chain length.
After sorting, iterate through words from shortest to longest. For each word, generate all possible predecessors by removing one character at each position. For each predecessor string that exists in the set of words (or in dp), we can consider dp[predecessor] + 1. Take the maximum. If none, dp[word] = 1. Keep track of the overall maximum.
Complexity: Sorting: O(N log N). For each word of length L, generating L predecessors (by removing one character each). So overall O(N * L_max). Since L_max <= 16 maybe? But in worst case could be large. But acceptable.
We need to return the maximum chain length. Optionally, we might want to return the chain itself? The problem statement says "find the longest string chain". It might ask for the length or the actual chain? Usually the problem asks for the length. But let's read: "Write a function to find the longest string chain." Could be length. But we can also return the chain if needed. But the classic problem asks for the length. We'll implement to return the length.
Alternatively, we could reconstruct the chain by storing predecessors. But we'll explain DP.
Implementation details:
- Sort words by length.
- Create a dictionary dp = {} to store the longest chain ending at each word.
- Initialize max_len = 0.
- For each word in sorted list:
current_len = 1
For i in range(len(word)):
pred = word[:i] + word[i+1:]
if pred in dp:
current_len = max(current_len, dp[pred] + 1)
dp[word] = current_len
max_len = max(max_len, current_len)
- return max_len
We also need to consider that there might be duplicate words? Usually words are unique. But if duplicates, we can convert to set first and then sort.
So we'll take words as input list, maybe convert to set to remove duplicates, then sort.
Edge cases: empty list returns 0.
Now explanation:
We sort words by length so that when processing a word, all possible predecessors (shorter by one) have already been processed and their dp values are computed. This is a typical DAG approach where edges go from shorter to longer words. DP state: dp[w] = longest chain ending at w. Transition: dp[w] = 1 + max{ dp[p] for p in predecessors of w }.
The predecessor check is done by generating all strings that can be obtained by removing one character from w and checking if that string exists in our set (or dp). Since we only need to consider words of length exactly one less, generating all L possibilities and checking membership in a set (or dp) is efficient.
Time complexity: O(N log N + N * L_max). Space: O(N) for dp and set.
Now produce code.
But the user might want a function with signature something like:
def longest_str_chain(words: List[str]) -> int:
We'll implement accordingly.
Let's also include explanation in the response.
We'll write a Python function and then explain DP.
We might also consider an alternative where we store all words in a set for O(1) membership check. But note: dp dictionary contains only words that are in the input and have been processed. Since we sorted by length, when checking pred, we need to check if pred is in the set of words (all words) but dp[pred] only exists if pred is in the words list. But we can use a set of all words to check existence quickly. Or we can rely on dp keys because we process in order and only add keys after processing. But careful: For a given word, we want to check if a predecessor exists in the original list, not just processed? Actually if predecessor exists in the list but hasn't been processed yet? Since we sorted by length, predecessors are shorter, so they would have been processed already. So if predecessor is in the list, it must have been processed because it's shorter. However, if we removed duplicates and sorted, we are processing all words of a given length together. But predecessors have length exactly one less, so they are processed in earlier iterations. So we can safely check dp dictionary for existence. But we need to be careful: what if there are multiple words of the same length? They are processed in arbitrary order within the same length, but predecessors are one length shorter, so they are all processed before we start processing words of the current length? Because we process in increasing order of length. So when processing a word of length L, all words of length L-1 have been processed. So dp contains all words of length < L. So checking dp is fine. But we should also check that pred is actually a word in the list. But if pred is not a word in the list, it won't be in dp. So we can just check if pred in dp. But note: if there are duplicate words, we might have removed them. But that's fine.
Thus we can use dp dict as both storage and membership check.
But we need to initialize dp as empty.
Alternatively, we can store all words in a set for membership, then use dp for values. That might be clearer.
We'll do:
words = sorted(set(words), key=len)
Then for each word, compute.
Let's test with an example:
words = ["a","b","ba","bca","bda","bdca"]
Sorted by length: ["a","b","ba","bca","bda","bdca"]
dp:
"a":1, "b":1
"ba": check removing 'b' -> "a" exists -> dp["a"]+1=2; removing 'a' -> "b" exists -> 2 -> so dp["ba"]=2
"bca": remove 'b' -> "ca"? not in dp; remove 'c' -> "ba"? exists dp["ba"]=2 -> 3; remove 'a' -> "bc"? not. So dp=3.
"bda": similarly -> "ba" -> 3.
"bdca": remove 'b' -> "dca"? no; remove 'd' -> "bca"? exists 3 -> 4; remove 'c' -> "bda"? 3 ->4; remove 'a' -> "bdc"? no. So dp=4.
max=4.
Thus answer 4.
Now produce code with appropriate comments.
Also we might want to return the actual chain? Usually just length. But we can extend if needed. The problem statement: "find the longest string chain." Might mean length. But sometimes they ask for the chain itself. We'll assume length.
We'll write a function that returns an integer.
Now explanation of DP:
- We define dp[w] as the length of the longest chain ending at w.
- Base: if w has no predecessor (i.e., no word of length len(w)-1 that can form w by adding a letter), then dp[w]=1.
- Transition: For each possible predecessor p (by removing one letter from w), if p exists in words and dp[p] is defined, then dp[w] = max(dp[p] + 1) over all p.
- Since we process words in increasing order of length, when computing dp[w], all dp[p] for shorter words are already computed.
- The answer is max(dp.values()).
We can also discuss why sorting by length is crucial: because we need to ensure that when processing a word, all its possible predecessors have been processed. This guarantees that dp values are available.
Now produce final answer.
Solution Explanation
We are given a list of words.
A string chain is a sequence word1, word2, ..., wordk where each word is a predecessor of the next.
wordA is a predecessor of wordB iff we can add exactly one character anywhere in wordA to obtain wordB.
Equivalently, wordA is a predecessor of wordB if |wordA| + 1 = |wordB| and wordA can be obtained by removing one character from wordB.
The task is to find the length of the longest possible chain.
Dynamic Programming Approach
We use dynamic programming where the state is:
dp[w] = length of the longest chain that ends with word w
Transition
For a word w of length L, any predecessor must have length L-1.
We generate all L possible strings that can be obtained by removing one character from w:
pred_i = w[0:i] + w[i+1:] for i in 0 .. L-1
If a predecessor pred_i exists in the input list, then we can extend the chain ending at pred_i by w:
dp[w] = max( dp[pred_i] + 1 ) over all valid predecessors
If no predecessor exists, the chain consisting of only w has length 1.
Order of processing
The transition relies on dp[pred] being already computed. Because every predecessor is shorter by exactly one character, we can guarantee this by processing words in increasing order of length. Thus we first sort the words by their length.
Algorithm
1. Remove duplicates (optional) and sort words by length.
2. Initialize an empty dictionary dp.
3. For each word w in sorted order:
cur = 1
For each i from 0 to len(w)-1:
pred = w[:i] + w[i+1:]
If pred in dp:
cur = max(cur, dp[pred] + 1)
dp[w] = cur
update global_max = max(global_max, cur)
4. Return global_max
Complexity Analysis
- Let
N be the number of words, L_max the maximum word length.
- Sorting:
O(N log N).
- For each word we generate at most
L predecessors → total O( Σ L ) = O(N * L_max).
- Dictionary look‑ups are
O(1) on average.
Overall time: O(N log N + N * L_max)
Space: O(N) for the dp dictionary and the sorted list.
Code (Python)
from typing import List
def longest_str_chain(words: List[str]) -> int:
"""
Returns the length of the longest possible string chain.
"""
# Remove duplicates and sort by length (ascending)
words_sorted = sorted(set(words), key=len)
dp = {} # word -> longest chain ending at this word
max_chain = 0
for word in words_sorted:
current_len = 1 # chain consisting of the word itself
# Try every possible predecessor by removing one character
for i in range(len(word)):
pred = word[:i] + word[i+1:]
if pred in dp:
current_len = max(current_len, dp[pred] + 1)
dp[word] = current_len
max_chain = max(max_chain, current_len)
return max_chain
Example
words = ["a","b","ba","bca","bda","bdca"]
print(longest_str_chain(words)) # Output: 4
# The chain: "a" -> "ba" -> "bca" -> "bdca" (or "b" -> "ba" -> "bda" -> "bdca")
Why DP Works
The problem has optimal substructure: a longest chain ending at w must be a longest chain ending at some predecessor p plus w.
The sorted order ensures that when we compute dp[w], all dp[p] are already known.
Thus the DP recurrence correctly builds the optimal solution from smaller subproblems.