You are given an array of words where each word consists of lowercase English letters.

Word A is a predecessor of word B if and only if we can insert exactly one letter anywhere in word A without changing the order of the other characters to make it equal to word B.

For example, "abc" is a predecessor of "abac", while "cba" is not a predecessor of "bcad".

A word chain is a sequence of words [word₁, word₂, ..., wordₖ] with k >= 1, where word₁ is a predecessor of word₂, word₂ is a predecessor of word₃, and so on. A single word is trivially a word chain with k == 1.

Return the length of the longest possible word chain with words chosen from the given list of words.

Input & Output

Example 1 — Basic Chain
$ Input: words = ["a","ba","bca","bda","bdca"]
Output: 4
💡 Note: One longest chain is: "a" → "ba" → "bca" → "bdca". Each word is formed by adding exactly one character to the previous word while maintaining order.
Example 2 — Multiple Chains
$ Input: words = ["xbc","pcxbcf","xb","cxbc","pcxbc"]
Output: 5
💡 Note: The longest chain is: "xb" → "xbc" → "cxbc" → "pcxbc" → "pcxbcf". Length is 5.
Example 3 — Single Word
$ Input: words = ["abde","abc","abd","abcde","ade","ae","1abde","1abc","1abcde"]
Output: 4
💡 Note: One longest chain is: "ae" → "ade" → "abde" → "abcde". Each step adds exactly one character.

Constraints

  • 1 ≤ words.length ≤ 1000
  • 1 ≤ words[i].length ≤ 16
  • words[i] only contains lowercase English letters

Visualization

Tap to expand
Longest String Chain INPUT words array (sorted by length) "a" len: 1 "ba" len: 2 "bca" len: 3 "bda" len: 3 "bdca" len: 4 Predecessor Example: a --> ba --> bda Insert 'b' at pos 0: a --> ba Insert 'd' at pos 1: ba --> bda Input Array: ["a","ba","bca","bda","bdca"] ALGORITHM STEPS 1 Sort by Length Process shorter words first 2 Init DP Map dp[word] = longest chain ending at word 3 Try Remove Each Char Check if predecessor exists 4 Update DP Value dp[word] = max(dp[pred] + 1) DP HashMap: "a": 1 "ba": 2 "bca": 3 "bda": 3 "bdca": 4 For "bdca": remove each char "dca","bca","bda","bdc" --> max dp = 3 FINAL RESULT Longest Chain Found: a ba bda bdca Chain Length: 4 words Output: 4 Status: OK a --> ba --> bda --> bdca Time: O(n * L^2) Key Insight: Use Dynamic Programming with HashMap. For each word, try removing each character one at a time. If the resulting string exists in the map, it's a valid predecessor. The DP value for current word is max(dp[predecessor] + 1). Sort words by length first to ensure predecessors are processed earlier. TutorialsPoint - Longest String Chain | Optimal DP Solution
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
125.0K Views
Medium-High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen