You are given an array of words where each word consists of lowercase English letters.
wordA is a predecessor of wordB if and only if we can insert exactly one letter anywhere in wordA without changing the order of the other characters to make it equal to wordB.
"abc" is a predecessor of "abac", while "cba" is not a predecessor of "bcad".A word chain is a sequence of words [word1, word2, ..., wordk] with k >= 1, where word1 is a predecessor of word2, word2 is a predecessor of word3, and so on. A single word is trivially a word chain with k == 1.
Return the length of the longest possible word chain with words chosen from the given list of words.
Example 1:
Input: words = ["a","b","ba","bca","bda","bdca"] Output: 4 Explanation: One of the longest word chains is ["a","ba","bda","bdca"].
Example 2:
Input: words = ["xbc","pcxbcf","xb","cxbc","pcxbc"] Output: 5 Explanation: All the words can be put in a word chain ["xb", "xbc", "cxbc", "pcxbc", "pcxbcf"].
Example 3:
Input: words = ["abcd","dbqca"] Output: 1 Explanation: The trivial word chain ["abcd"] is one of the longest word chains. ["abcd","dbqca"] is not a valid word chain because the ordering of the letters is changed.
Constraints:
1 <= words.length <= 10001 <= words[i].length <= 16words[i] only consists of lowercase English letters.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
To solve the Longest String Chain problem using a brute force strategy, we want to explore every conceivable sequence of words to see which chain of word building can grow the longest. By exhaustively testing all combinations of starting words and adding one letter at a time, we ensure we eventually discover the absolute longest chain possible.
Here's how the algorithm would work step-by-step:
def longestStrChain(words): def check_predecessor(shorter_word, longer_word): if len(longer_word) != len(shorter_word) + 1: return False shorter_index = 0 longer_index = 0 while longer_index < len(longer_word): if shorter_index < len(shorter_word) and shorter_word[shorter_index] == longer_word[longer_index]: shorter_index += 1 longer_index += 1 return shorter_index == len(shorter_word) def explore_chain(current_word, word_collection): max_chain_depth = 1 for next_word in word_collection: if check_predecessor(current_word, next_word): max_chain_depth = max(max_chain_depth, 1 + explore_chain(next_word, word_collection)) return max_chain_depth # Exhaustively test every word as a potential starting point to find the global maximum chain length global_maximum_length = 0 for starting_word in words: current_chain_length = explore_chain(starting_word, words) global_maximum_length = max(global_maximum_length, current_chain_length) return global_maximum_lengthTo find the longest possible chain of words where each step adds a single letter, the optimal strategy sorts the words by length and figures out the best chain ending at each word. By building the answers for shorter words first, we can easily find the longest chain for any longer word by checking its slightly shorter variations.
Here's how the algorithm would work step-by-step:
def longest_str_chain(words_list):
words_list.sort(key=len)
chain_lengths = {}
max_chain_length = 1
# Sorting by length ensures shorter predecessors are always processed before longer words.
for current_word in words_list:
current_chain = 1
for character_index in range(len(current_word)):
predecessor_word = current_word[:character_index] + current_word[character_index + 1:]
if predecessor_word in chain_lengths:
current_chain = max(current_chain, chain_lengths[predecessor_word] + 1)
chain_lengths[current_word] = current_chain
# Tracking the global maximum allows us to return the longest chain found overall.
max_chain_length = max(max_chain_length, current_chain)
# Returning the maximum recorded chain length gives the final answer for the problem.
return max_chain_length| Case | How to Handle |
|---|---|
| Empty or null input array of words | Return zero immediately since no word chain can be formed. |
| Array containing only a single word of length one | Return one as the default maximum chain length since a single word forms a valid chain of length one. |
| Words of identical lengths present in the input | Sorting by length ensures words of the same length do not form chains with each other since a predecessor must be strictly one character shorter. |
| Duplicate words existing within the input array | Hash map stores the maximum chain length for each unique word, safely ignoring or overriding identical predecessor values without affecting the result. |
| Maximum possible input constraints with thousands of long strings | An O(N * L^2) dynamic programming approach with string length sorting ensures optimal scalability well within time limits. |
| No valid word chain exists where any word can be derived from another | Every word defaults to a chain length of one in the hash map, resulting in a correct maximum length return value of one. |
| Character insertion at the very beginning or end of a word | The predecessor check correctly handles boundary deletions by slicing the string from index zero to i combined with i plus one to the end. |
| Memory limits exceeded due to large string storage in hash map structures | Reusing references and storing only integer chain lengths in the hash map prevents excessive memory consumption. |