Longest String Chain

Pattern: LIS family

medium

Word a is a predecessor of b when inserting one letter into a gives b. Sort words by length; the longest chain ending at a word is 1 + the best over every word made by deleting one of its letters.

The problem

Return the length of the longest chain of words from the list where each word is the previous one with exactly one letter inserted somewhere.

Think first

  • Which words can come before a given word?
  • How do you find them quickly?
  • In what order should words be processed?

Hints

    Brute force, and why it fails

    Compare every pair of words: O(n² × L).

    The key insight

    A word has only L possible predecessors, each found by deleting one letter, so a hash map replaces the pair loop.

    Dry run

    [a, b, ba, bca, bda, bdca]. a: 1, b: 1, ba: 2 (from a or b).

    Step 1 of 2

    The plan

    sort by length; best = {}
    for w: best[w] = 1 + max(best.get(w without letter i, 0) for each i)
    return max(best)
    

    Complexity

    Time
    O(n × L²)
    Space
    O(n × L)

    L deletions per word, each building a string of length L.

    Edge cases

    • One word: 1.
    • No chains: 1.
    • Duplicate words.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int longestStrChain(String[] words) {
            String[] w = words.clone();
            Arrays.sort(w, (a, b) -> a.length() - b.length());   // shorter words first: a predecessor is always shorter
            Map<String, Integer> best = new HashMap<>();         // word -> the longest chain ending at it
            int answer = 0;
            for (String word : w) {
                int b = 1;
                for (int i = 0; i < word.length(); i++) {        // every word one letter shorter is a possible predecessor
                    String shorter = word.substring(0, i) + word.substring(i + 1);
                    b = Math.max(b, best.getOrDefault(shorter, 0) + 1);
                }
                best.put(word, b);
                answer = Math.max(answer, b);
            }
            return answer;
        }
    }

    C++

    class Solution {
    public:
        int longestStrChain(vector<string>& words) {
            vector<string> w(words);
            sort(w.begin(), w.end(), [](const string& a, const string& b) { return a.size() < b.size(); });   // shorter first
            unordered_map<string, int> best;        // word -> the longest chain ending at it
            int answer = 0;
            for (const string& word : w) {
                int b = 1;
                for (size_t i = 0; i < word.size(); i++) {   // every word one letter shorter is a possible predecessor
                    string shorter = word.substr(0, i) + word.substr(i + 1);
                    auto it = best.find(shorter);
                    if (it != best.end()) b = max(b, it->second + 1);
                }
                best[word] = b;
                answer = max(answer, b);
            }
            return answer;
        }
    };

    Python

    class Solution:
        def longestStrChain(self, words: list[str]) -> int:
            best = {}                               # word -> the longest chain ending at it
            for word in sorted(words, key=len):     # shorter words first: a predecessor is always shorter
                best[word] = 1 + max((best.get(word[:i] + word[i + 1:], 0) for i in range(len(word))), default=0)
            return max(best.values())

    Common mistakes

    • Allowing letters to be reordered.
    • Processing longer words first.

    Similar problems