oneby7

1-D Dynamic Programming Increasing subsequences

531. Longest String Chain

Medium

You are given a list of words words, each made of lowercase English letters. Return the length of the longest word chain you can build from them.

A word a is a predecessor of a word b when inserting exactly one letter into a gives b. The letter can go at the front, between two letters or at the end, and the letters of a keep their order. So "cat" is a predecessor of "cart", but "ab" is not a predecessor of "bca".

A word chain is a sequence of words from the list, taken in any order, where each word is a predecessor of the next one. Its length is the number of words in it, so a single word is a chain of length 1.

Example 1

Input: words = ["chart", "at", "cat", "t", "cart", "rat", "hat"]

Output: 5

Explanation: The chain "t", "at", "cat", "cart", "chart" adds one letter at each step: an a at the front, a c at the front, an r in the middle and an h in the middle. "rat" and "hat" also follow "at", but nothing follows them.

Example 2

Input: words = ["on", "now", "own"]

Output: 2

Explanation: "own" is "on" with a w in the middle. "now" has the same letters as "own", but making it from "on" would move letters around, so it cannot follow "on".

Example 3

Input: words = ["dog", "dog", "cat"]

Output: 1

Explanation: Each step adds exactly one letter, so a word cannot follow a copy of itself. No word is a predecessor of another, and the longest chain is any single word.

Check your understanding

Work out the answer for this input before you write any code.

words = ["seat", "mates", "a", "tea", "at", "eat"]

Constraints

  • 1 ≤ words.length ≤ 105
  • 1 ≤ words[i].length ≤ 16
  • words[i] holds only lowercase English letters.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.