SDE & MLE Prep

1048. Longest String Chain

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())