Longest String Chain
Medium
Topics
wordA is a predecessor of wordB if inserting exactly one letter anywhere in wordA, without reordering anything else, produces wordB. So "abc" is a predecessor of "abac", of "abcd" and of "xabc" — the new letter may go anywhere — but not of "acb", which would need a reordering, nor of "abcde", which is two letters longer.
A word chain is a sequence of words where each is a predecessor of the next. A single word is a chain of length 1.
Given a list of words, return the length of the longest chain that can be built from them.
Example 1
Input: words = ["a","b","ba","bca","bda","bdca"] Output: 4 Explanation: One longest chain is a, ba, bda, bdca.
Example 2
Input: words = ["xbc","pcxbcf","xb","cxbc","pcxbc"] Output: 5 Explanation: xb, xbc, cxbc, pcxbc, pcxbcf uses every word.
Example 3
Input: words = ["abcd","dbqca"] Output: 1 Explanation: Neither is a predecessor of the other, so no chain is longer than a single word.
Constraints
- 1 <= words.length <= 1000
- 1 <= words[i].length <= 16
- words[i] consists of lowercase English letters
Editorial — intuition, approach, complexity and pitfalls
Intuition
A predecessor is always exactly one letter shorter, so a chain’s words have strictly increasing lengths. That means the words can be processed in order of length and every chain is built left to right, shortest first — there is nothing to search backwards for.
The second move is to reverse the direction of the question. Asking "which words can follow this one" means generating all the ways to insert a letter: 26 letters times 17 positions. Asking "which word could this one follow" means deleting one letter, which gives only as many candidates as the word has letters — at most 16.
So for each word, try removing each of its letters and look the result up among the words already processed. The longest chain ending at this word is one more than the best chain ending at any of those predecessors, and the answer is the largest value recorded.
Approach
- Sort the words by increasing length, so every possible predecessor is processed before the word itself.
- Keep a map from word to the length of the longest chain ending at that word.
- For each word, start its best at 1. For each position, delete the letter at that position and look the shorter string up in the map; if it is there, the chain through it is one longer than its recorded value.
- Record the word’s best and keep the maximum across all words.
Walkthrough
words = ["a","b","ba","bca","bda","bdca"]
sorted by length: a, b, ba, bca, bda, bdca
word deletions that are known words best
a -- 1
b -- 1
ba "a" (1), "b" (1) 2
bca "ca" no, "ba" (2), "bc" no 3
bda "da" no, "ba" (2), "bd" no 3
bdca "dca" no, "bca" (3), "bda" (3),
"bdc" no 4
answer 4
Each word tries at most as many candidates as it has
letters, rather than the 26 x length insertions the forward
direction would need.Complexity
- Time — O(n * L^2): n words, each trying L deletions, each costing O(L) to build the shorter string. With L capped at 16 that is small.
- Space — O(n * L): the map holds every word.
Common Pitfalls
- Generating successors by insertion rather than predecessors by deletion. Both are correct and the insertion direction is 26 times more work.
- Not sorting by length. A word processed before its predecessor reads a missing or stale entry, and the chain comes out short.
- Sorting lexicographically.
"ba"sorts before"a"in no useful way here; it is length that orders a chain. - Requiring the inserted letter to go at the end.
"bca"follows"ba"by an insertion in the middle. - Starting a word’s best at 0. A lone word is already a chain of length 1.
Full Solution — all languages
class Solution:
def longestStrChain(self, words):
best = {}
answer = 0
for word in sorted(words, key=len):
longest = 1
for i in range(len(word)):
shorter = word[:i] + word[i + 1:]
if shorter in best:
longest = max(longest, best[shorter] + 1)
best[word] = longest
answer = max(answer, longest)
return answerimport java.util.*;
class Solution {
public int longestStrChain(String[] words) {
String[] sorted = words.clone();
Arrays.sort(sorted, (x, y) -> Integer.compare(x.length(), y.length()));
Map<String, Integer> best = new HashMap<>();
int answer = 0;
for (String word : sorted) {
int longest = 1;
for (int i = 0; i < word.length(); i++) {
String shorter = word.substring(0, i) + word.substring(i + 1);
Integer seen = best.get(shorter);
if (seen != null) longest = Math.max(longest, seen + 1);
}
best.put(word, longest);
answer = Math.max(answer, longest);
}
return answer;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int longestStrChain(vector<string>& words) {
vector<string> sorted_ = words;
sort(sorted_.begin(), sorted_.end(), [](const string& x, const string& y) {
return x.size() < y.size();
})
;
unordered_map<string, int> best;
int answer = 0;
for (const string& word : sorted_) {
int longest = 1;
for (size_t i = 0; i < word.size(); i++) {
string shorter = word.substr(0, i) + word.substr(i + 1);
auto it = best.find(shorter);
if (it != best.end()) longest = max(longest, it->second + 1);
}
best[word] = longest;
answer = max(answer, longest);
}
return answer;
}
};/**
* @param {string[]} words
* @return {number}
*/ var longestStrChain = function(words) {
const sorted = words.slice().sort((x, y) => x.length - y.length);
const best = new Map();
let answer = 0;
for (const word of sorted) {
let longest = 1;
for (let i = 0; i < word.length; i++) {
const shorter = word.slice(0, i) + word.slice(i + 1);
if (best.has(shorter)) longest = Math.max(longest, best.get(shorter) + 1);
}
best.set(word, longest);
answer = Math.max(answer, longest);
}
return answer;
};