Longest String Chain

Dynamic Programming LIS Easy

Given an array of strings words[], the task is to return the longest string chain. A string chain is defined as a sequence of words where:


Each word (except the first) can be formed by inserting exactly one character into the previous word.

The first word of the chain can be any word from the words[] array.

The task is to determine the length of the longest chain.

Examples:

Input: words = ["a", "ab", "abc", "abcd", "abcde"]

Output: 5

Explanation: The longest chain is ["a", "ab", "abc", "abcd", "abcde"].

Each word in the chain is formed by adding exactly one character to the previous word.

Input: words = ["dog", "dogs", "dots", "dot", "d", "do"]

Output: 4

Explanation: The longest chain is ["d", "do", "dot", "dots"].

Each word is formed by inserting one character into the previous word.

Input: words = ["a", "aa", "aaa", "aaaa", "b", "bb", "bbb"]

Constraints

  • 1 <= words.length <= 1000
  • 1 <= words[i].length <= 20
  • words[i] only consists of lowercase English letters.

Hints

  • A Dynamic Programming (DP) approach efficiently solves this problem by Sorting words[] by length ensures that every word comes after all potential predecessors.
  • "Using a DP array (dp[word]) to store the longest chain ending at each word. Iterating through each word and checking all possible predecessors by removing one character at a time."