You are given an array of words where each word consists of lowercase English letters. Your task is to find the longest possible word chain that can be formed from these words.

What is a Word Chain?

A word chain is a sequence of words where each word is a predecessor of the next word. 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 other characters) to make it equal to word B.

Examples of predecessors:

  • "abc" is a predecessor of "abxc" (insert 'x' at position 2)
  • "abc" is a predecessor of "xabc" (insert 'x' at position 0)
  • "cba" is NOT a predecessor of "bcad" (would require reordering)

Goal: Return the length of the longest possible word chain. A single word is trivially a word chain of length 1.

Input & Output

example_1.py โ€” Basic Chain
$ Input: ["a","b","ba","bca","bda","bdca"]
โ€บ Output: 4
๐Ÿ’ก Note: One of the longest word chains is ["a","ba","bda","bdca"] with length 4. Another valid chain is ["a","ba","bca","bdca"].
example_2.py โ€” Multiple Chains
$ Input: ["xbc","pcxbcf","xb","cxbc","pcxbc"]
โ€บ Output: 5
๐Ÿ’ก Note: The longest chain is ["xb","xbc","cxbc","pcxbc","pcxbcf"] with length 5.
example_3.py โ€” Single Word
$ Input: ["abde","abc","abd","abcde","ade","ae","1abde","1abc","1abd","1abcde","1ade","1ae"]
โ€บ Output: 4
๐Ÿ’ก Note: Multiple chains of length 4 exist, such as ["ae","ade","abde","abcde"].

Constraints

  • 1 โ‰ค words.length โ‰ค 1000
  • 1 โ‰ค words[i].length โ‰ค 16
  • words[i] only contains lowercase English letters
  • All strings are unique

Visualization

Tap to expand
Word Chain Evolution ProcessGeneration 1 (Length 1):abGeneration 2 (Length 2):baGeneration 3 (Length 3):bcabdaGeneration 4 (Length 4):bdcaDP State:dp['a'] = 1dp['b'] = 1dp['ba'] = 2dp['bca'] = 3dp['bda'] = 3dp['bdca'] = 4Max Chain Length: 4
Understanding the Visualization
1
Sort by Complexity
Arrange words by length - simpler forms must come before complex ones
2
Build Incrementally
For each word, check if removing any character gives us a known predecessor
3
Track Best Path
Remember the longest chain ending at each word using memoization
4
Find Maximum
Return the length of the longest chain found
Key Takeaway
๐ŸŽฏ Key Insight: By processing words in length order and using dynamic programming, we ensure that when we process a word of length n, all its potential predecessors of length n-1 have already been processed and their optimal chain lengths are known.
Asked in
Google 42 Amazon 38 Meta 31 Microsoft 25
67.2K Views
High Frequency
~25 min Avg. Time
1.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