Longest String Chain Problem
Description
LeetCode Problem 1048.
You are given an array of words where each word consists of lowercase English letters.
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 the other characters to make it equal to word_B.
- For example,
"abc"is a predecessor of"abac", while"cba"is not a predecessor of"bcad".
A word chain is a sequence of words [word_1, word_2, ..., word_k] with k >= 1, where word_1 is a predecessor of word_2, word_2 is a predecessor of word_3, and so on. A single word is trivially a word chain with k == 1.
Return the length of the longest possible word chain with words chosen from the given list of words.
Example 1:
Input: words = ["a","b","ba","bca","bda","bdca"]
Output: 4
Explanation: One of the longest word chains is ["a","ba","bda","bdca"].
Example 2:
Input: words = ["xbc","pcxbcf","xb","cxbc","pcxbc"]
Output: 5
Explanation: All the words can be put in a word chain ["xb", "xbc", "cxbc", "pcxbc", "pcxbcf"].
Example 3:
Input: words = ["abcd","dbqca"]
Output: 1
Explanation: The trivial word chain ["abcd"] is one of the longest word chains.
["abcd","dbqca"] is not a valid word chain because the ordering of the letters is changed.
Constraints:
1 <= words.length <= 10001 <= words[i].length <= 16words[i]only consists of lowercase English letters.
Solution
Approach: Dynamic Programming + Hash Map
A predecessor is always exactly one letter shorter. So if we handle the words from shortest to longest, every possible predecessor of a word has already been handled when we reach it.
Let chain[w] be the length of the longest chain that ends with word w. Going the other way round from the definition, a predecessor of w is w with one letter deleted. A word has at most 16 letters, so we can try every deletion:
chain[w] = 1 + max(chain[w with letter i deleted]) over the deletions that are in the map
and chain[w] = 1 if none of them is a word in the list. The answer is the largest chain value.
Generating predecessors by deletion is much faster than comparing every pair of words, and it never has to check the letter order separately: deleting one letter keeps the others in order by construction.
Complexity: O(n log n + n * L2) time and O(n * L) space, where L is the maximum word length (building each of the L predecessors costs O(L)).
class Solution:
def longestStrChain(self, words: List[str]) -> int:
chain = {} # word -> length of the longest chain ending with it
# Shorter words first, so every predecessor is done before the words built on it.
for w in sorted(words, key=len):
# A predecessor is w with one letter deleted: try each position.
chain[w] = max(chain.get(w[:i] + w[i + 1:], 0) + 1 for i in range(len(w)))
return max(chain.values())