sagelearnai

Longest String Chain

Difficulty: Medium · Pattern: 2-D Dynamic Programming · LeetCode #1048

a is a predecessor of b if you can insert exactly one letter anywhere in a to get b. A word chain is a sequence in which each word is a predecessor of the next. Return the length of the longest possible chain using words from words.

Examples

text
["a","b","ba","bca","bda","bdca"]                →  4   (a → ba → bda → bdca)
["xbc","pcxbcf","xb","cxbc","pcxbc"]             →  5
["abcd","dbqca"]                                  →  1

Hints

  1. Process the words from shortest to longest.
  2. For each word, its predecessors are found by deleting one character, so look those up in a hash map.

Approach

Sort by length. dp[w] = 1 + max(dp[w[:i] + w[i+1:]]) over the deletions that appear in dp. The answer is max(dp.values()).

Deleting one character (L options) is far cheaper than comparing every pair of words. Total O(n log n + n · L²), counting the cost of building the strings.

Complexity

Time: O(n log n + n · L²). Space: O(n · L).

Python solution
def longestStrChain(words):
    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())
JavaScript solution
function longestStrChain(words) {
  const dp = new Map();
  let best = 0;
  for (const w of [...words].sort((a, b) => a.length - b.length)) {
    let cur = 1;
    for (let i = 0; i < w.length; i++) cur = Math.max(cur, (dp.get(w.slice(0, i) + w.slice(i + 1)) || 0) + 1);
    dp.set(w, cur);
    best = Math.max(best, cur);
  }
  return best;
}