Taro Logo

Longest String Chain

#12 Most AskedMedium
0 views
Topics:
ArraysStringsDynamic Programming

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.

  • For example, "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 <= 1000
  • 1 <= words[i].length <= 16
  • words[i] only consists of lowercase English letters.

Solution


Clarifying Questions

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:

  1. What is the maximum number of words in the array and the maximum possible length of a single word?
  2. Are there any duplicate words in the input array, and if so, should they be treated as separate instances or ignored?
  3. Can the input array be empty or contain a single word, and what should be returned in such cases?
  4. Does the word chain require the words to be given in any specific initial order in the input array, or can we process them in any order?
  5. Are all characters in the words strictly lowercase English letters, or could there be uppercase letters, spaces, or special characters?

Brute Force Solution

Approach

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:

  1. Gather the complete collection of words provided in the problem.
  2. Pick any word from the collection to serve as the beginning of a potential chain.
  3. Look through the remaining words in the collection to find one that is identical to your current word with just one extra letter added anywhere in it.
  4. If you find such a word, treat it as the next link in your current chain and repeat the search process using this new word as your base.
  5. Continue this process of adding one letter at a time until you can no longer find any valid next word in the collection.
  6. Once your chain hits a dead end, measure how many words were in that specific chain and remember that total.
  7. Now, go back and repeat this entire journey starting from every other possible word in the original collection, as well as trying different paths along the way.
  8. Keep track of the lengths of every single chain you build during this exhaustive exploration.
  9. After you have tried every possible combination and path, look at all your recorded chain lengths and select the highest number as your final answer.

Code Implementation

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_length

Big(O) Analysis

Time Complexity
O(n * 2^n) – To analyze the brute force strategy, let n be the number of words in the input collection. We must exhaustively explore every possible starting word and recursively test all valid paths of one-letter additions, resulting in a binary-like branching factor where each word can potentially lead to multiple subsequent chains. In the worst-case scenario, this exploration evaluates on the order of 2^n possible paths for each of the n starting words. Combining the initial choice of starting words with the exhaustive recursive search yields approximately n * 2^n operations, which simplifies in Big O notation to O(n * 2^n).
Space Complexity
O(N) – The brute force exploration requires auxiliary memory to keep track of visited locations, temporary paths, and recorded chain lengths for every possible combination during the exhaustive exploration. As the total number of words N increases, these tracking variables and path storage grow proportionally to store the states of the evolving chains. Therefore, the extra auxiliary memory scales linearly with the input size N, resulting in a space complexity of O(N).

Optimal Solution

Approach

To 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:

  1. Gather all the words and arrange them in order from shortest to longest.
  2. Consider the shortest words first, knowing that each of them naturally starts a chain of length one.
  3. Move on to slightly longer words and check all the possible ways to remove just one letter from the current word.
  4. Look to see if any of those slightly shorter versions have already been seen and successfully chained.
  5. If a shorter version exists in our history, take the longest chain built up to that point and add one more step for the current word.
  6. Keep track of the best chain length found so far as you process every word from shortest to longest.
  7. Once all words have been checked, the maximum chain length recorded will be your final answer.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(n * L^2) – The time complexity is driven by sorting the n words by their length, which takes O(n log n) time, and then processing each word. For each of the n words, which has a maximum length L, we generate L possible predecessor words by removing one letter at a time. Looking up each predecessor in our history takes O(L) time for string slicing and hashing, resulting in O(L^2) work per word. Multiplying the n words by the O(L^2) cost to check all single-letter variations yields a total time complexity of O(n * L^2).
Space Complexity
O(N) – To analyze the auxiliary space, let N be the total number of words in the input array. We allocate a hash map to keep track of the longest chain length ending at each word, which stores up to N entries. Additionally, sorting the words by length requires extra space depending on the sorting implementation, but this is bounded by the number of words. Therefore, the memory consumed by our history tracking and sorted arrangement scales directly with the input size N, simplifying to Big O of N space complexity.

Edge Cases

Empty or null input array of words
How to Handle:
Return zero immediately since no word chain can be formed.
Array containing only a single word of length one
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Reusing references and storing only integer chain lengths in the hash map prevents excessive memory consumption.
0/29 completed