Overview
This is a variation of LIS, but on strings. Instead of checking every previous word, we systematically remove one character to find predecessors.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Given a list of words, find the length of the longest chain where each word adds exactly one letter anywhere to the previous word.
This is a variation of LIS, but on strings. Instead of checking every previous word, we systematically remove one character to find predecessors.
Because a predecessor must be strictly shorter, we first sort the array of words by length. This guarantees we process predecessors before successors.
Instead of an array `dp[i]`, we use a hash map `dp[word]` mapping the string to its chain length. This provides O(1) lookups for predecessors.
For a word, loop through each character, remove it, and check if the resulting string is in the hash map. Update the max length accordingly.