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 ProblemFind longest chain where each word is predecessor of nextInput Words["a","ba","bca","bda","bdca"]"a""ba""bca""bdca""bda"Valid ChainNo valid successorLongest ChainLength: 4"a" → "ba" → "bca" → "bdca"Each step: add exactly one character while preserving order
Understanding the Visualization
1
Input
Array of words with different lengths
2
Process
Find predecessor relationships and build chains
3
Output
Return length of longest possible chain
Key Takeaway
🎯 Key Insight: Sort by length first - predecessors are always shorter, making DP transitions clear
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