1048. Longest String Chain
Asked at 15Google25Microsoft20Bloomberg18Amazon13Meta12Infosys39Moloco92Two Sigma90Wix87Tekion74Agoda48DE Shaw47PayPal42Atlassian34LinkedIn20
Problem
Word A is a predecessor of word B if inserting exactly one letter anywhere in A gives B. A word chain is a sequence where each word is a predecessor of the next. Return the length of the longest chain you can build from words.
Example: ["a","b","ba","bca","bda","bdca"] → 4 (a → ba → bda → bdca)
Constraints: up to 1000 words of length ≤ 16.
Sort words by length. dp[w] = 1 + max(dp[w without one char]) over the words you can get by deleting one character.
Complexity: O(n · L²).
class Solution:
def longestStrChain(self, words: List[str]) -> int:
dp = {}
for w in sorted(words, key=len):
dp[w] = 1 + max((dp.get(w[:i] + w[i + 1:], 0) for i in range(len(w))), default=0)
return max(dp.values())
assert Solution().longestStrChain(["a", "b", "ba", "bca", "bda", "bdca"]) == 4
assert Solution().longestStrChain(["xbc", "pcxbcf", "xb", "cxbc", "pcxbc"]) == 5
assert Solution().longestStrChain(["abcd", "dbqca"]) == 1
class Solution {
public int longestStrChain(String[] words) {
Arrays.sort(words, (a, b) -> a.length() - b.length());
Map<String, Integer> dp = new HashMap<>();
int best = 0;
for (String w : words) {
int cur = 1;
for (int i = 0; i < w.length(); i++)
cur = Math.max(cur, dp.getOrDefault(w.substring(0, i) + w.substring(i + 1), 0) + 1);
dp.put(w, cur);
best = Math.max(best, cur);
}
return best;
}
}
func longestStrChain(words []string) int {
sort.Slice(words, func(i, j int) bool { return len(words[i]) < len(words[j]) })
dp := map[string]int{} // longest chain ending at word
best := 0
for _, w := range words {
dp[w] = 1
for i := 0; i < len(w); i++ { // predecessor: w with one letter removed
if p, ok := dp[w[:i]+w[i+1:]]; ok {
dp[w] = max(dp[w], p+1)
}
}
best = max(best, dp[w])
}
return best
}