Longest String Chain

You are given an array of words made of lowercase letters. A word A is a predecessor of word B if you can insert exactly one letter anywhere in A, without reordering its other letters, to get B. A word chain is a sequence where each word is a predecessor of the next; a single word is a chain of length 1. Return the length of the longest word chain you can build from words in the list.

30:00

Longest String Chain
medium
Free written solution
Topics
Companies

You are given an array of words made of lowercase letters. A word A is a predecessor of word B if you can insert exactly one letter anywhere in A, without reordering its other letters, to get B. A word chain is a sequence where each word is a predecessor of the next; a single word is a chain of length 1. Return the length of the longest word chain you can build from words in the list.

Example 1:
Input: {"words":["a","b","ba","bca","bda","bdca"]}
Output: 4
Constraints:
  • 1≤words.length≤10001 \leq \text{words.length} \leq 1000

  • 1≤words[i].length≤161 \leq \text{words}[i].\text{length} \leq 16

  • words[i]\text{words}[i] consists only of lowercase English letters.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"words":["a","b","ba","bca","bda","bdca"]}

There are 6 words. A chain grows one inserted letter at a time, so a word's predecessor is always exactly one letter shorter.

len 1

a

?

b

?

len 2

ba

?

len 3

bca

?

bda

?

len 4

bdca

?
current word
predecessor found
longest chain
badge = chain length ending at that word
Variables
VariableValue
best0
DepthFunction Call
Stack empty
0/30