Longest String Chain (LeetCode 1048): Solution and Explanation
Given a list of lowercase words, find the longest sequence where each word is the previous word with exactly one letter inserted. A single word counts as a chain of length 1.
Intuition
Going forward from a word means guessing which letter to insert and where, which is 26 times the work. Going backward is cheap: a word of length L has only L predecessors, one for each letter you could delete.
A predecessor is always exactly one letter shorter. If the words are processed from shortest to longest, every predecessor of a word has already been finished when the word comes up.
That makes it a plain DP keyed by the word itself: the longest chain ending at w is one more than the best chain ending at any of its deletions that is in the list.
Approach: Sort by length, DP over one-letter deletions
- Sort
wordsby length. - Keep a hash map
dpfrom word to the longest chain ending at that word. - For each word
w, start withcur = 1. For each positioni, formprevby deletingw[i]. Ifprevis indp, setcur = max(cur, dp[prev] + 1). - Store
dp[w] = curand update the overall best. Return the best.
Step-by-step example
words = ["a","b","ba","bca","bda","bdca"]
- After sorting by length the order is a, b, ba, bca, bda, bdca. "a" and "b" have only the empty string as a deletion, so both get 1.
- "ba": deleting "b" gives "a" (1) and deleting "a" gives "b" (1), so dp["ba"] = 2.
- "bca": deleting "c" gives "ba" (2), so dp["bca"] = 3. "bda" works the same way and also gets 3.
- "bdca": deleting "c" gives "bda" (3) and deleting "d" gives "bca" (3), so dp["bdca"] = 4. The answer is 4, for example a -> ba -> bda -> bdca.
Code: Python, Java, C++
1class Solution:
2 def longestStrChain(self, words: List[str]) -> int:
3 words.sort(key=len)
4 dp = {}
5 best = 0
6 for w in words:
7 cur = 1
8 for i in range(len(w)):
9 prev = w[:i] + w[i + 1:]
10 if prev in dp:
11 cur = max(cur, dp[prev] + 1)
12 dp[w] = cur
13 best = max(best, cur)
14 return best1class Solution {
2 public int longestStrChain(String[] words) {
3 Arrays.sort(words, (a, b) -> a.length() - b.length());
4 Map<String, Integer> dp = new HashMap<>();
5 int best = 0;
6 for (String w : words) {
7 int cur = 1;
8 for (int i = 0; i < w.length(); i++) {
9 String prev = w.substring(0, i) + w.substring(i + 1);
10 if (dp.containsKey(prev)) {
11 cur = Math.max(cur, dp.get(prev) + 1);
12 }
13 }
14 dp.put(w, cur);
15 best = Math.max(best, cur);
16 }
17 return best;
18 }
19}1class Solution {
2public:
3 int longestStrChain(vector<string>& words) {
4 sort(words.begin(), words.end(), [](const string& a, const string& b) { return a.size() < b.size(); });
5 unordered_map<string, int> dp;
6 int best = 0;
7 for (const string& w : words) {
8 int cur = 1;
9 for (int i = 0; i < (int)w.size(); i++) {
10 string prev = w.substr(0, i) + w.substr(i + 1);
11 auto it = dp.find(prev);
12 if (it != dp.end()) {
13 cur = max(cur, it->second + 1);
14 }
15 }
16 dp[w] = cur;
17 best = max(best, cur);
18 }
19 return best;
20 }
21};Time and space complexity
O(n log n + n * L^2)
Sorting costs O(n log n). Each of the n words tries L deletions, and building and hashing each shorter string costs O(L). L is at most 16.
O(n * L)
The map stores every word once.
Other approaches
Pairwise predecessor check (LIS style) (time O(n^2 * L), space O(n))
Sort by length, then for every pair of words whose lengths differ by one, check with two pointers whether one is a predecessor of the other, like the O(n^2) Longest Increasing Subsequence DP. Simple, but up to a million pair checks for 1000 words.
Memoized DFS from each word (time O(n * L^2), space O(n * L))
Recursively ask for the longest chain ending at a word by trying its deletions, caching results in a map. No sort is needed because the recursion only goes to shorter words.
Common mistakes
- Processing words in input order. A word's predecessor might appear later in the list and would still be missing from the map.
- Trying insertions instead of deletions. It works but costs 26 times more lookups.
- Assuming the chain must use adjacent words or keep letters at the same positions. The inserted letter can go anywhere.
- Treating a reordered word as a successor. "abcd" to "dbqca" changes the letter order, so it is not a chain step.
Frequently asked questions
Why sort by length and not alphabetically?
The DP only needs every predecessor to be finished before its successor. Predecessors are exactly one letter shorter, so length order guarantees that. Alphabetical order does not.
Does the order of words with the same length matter?
No. Words of the same length can never be predecessors of each other, so any order among them gives the same answer.
Can the answer be 1?
Yes. If no word is a one-letter deletion of another, every word is its own chain of length 1.
How is this related to Longest Increasing Subsequence?
Both find the longest path in a DAG built on sorted items. Here the edges are one-letter deletions, which a hash map finds directly, so we avoid comparing every pair.