
Sponsored
Sponsored
This approach involves sorting the array of words based on their lengths, which helps in easily recognizing the potential predecessors. Then, utilize a dynamic programming technique to build up the solution. For each word, check all words that are predecessors and update the maximum chain length accordingly.
Time Complexity: O(n^2 * l), where n is the number of words and l is the average length of each word. The sorting step contributes O(n log n) but checking each predecessor might happen in O(n^2). The maximum comparison takes O(l) time.
Space Complexity: O(n) for the dp array.
1class Solution:
2 def longestStrChain(self, words):
3 words.sort(key=len)
4 dp = {}
5 max_len = 1
6
7 for word in words:
8 dp[word] = 1
9 for i in range(len(word)):
10 prev = word[:i] + word[i+1:]
11 if prev in dp:
12 dp[word] = max(dp[word], dp[prev] + 1)
13 max_len = max(max_len, dp[word])
14
15 return max_len
16
17# Example usage:
18solution = Solution()
19words = ["a", "b", "ba", "bca", "bda", "bdca"]
20print(solution.longestStrChain(words))This Python solution uses a dictionary to store the longest chain length for each word. It sorts the list of words based on their lengths and iteratively finds the longest predecessor chain using substring checks.
This approach models the words as nodes in a graph and links words via edges if one is a predecessor of the other. The goal is to find the longest path in this directed acyclic graph (DAG), which represents the longest word chain.
Time Complexity: O(n^2 * l), where n is the number of words and l is the average word length as this is similar to a dynamic programming solution.
Space Complexity: O(n) for the dynamic programming path length array.
1using System.Collections.Generic;
public class Solution {
public int LongestStrChain(string[] words) {
Array.Sort(words, (a, b) => a.Length.CompareTo(b.Length));
Dictionary<string, int> dp = new Dictionary<string, int>();
int maxLen = 1;
foreach (string word in words) {
dp[word] = 1;
for (int i = 0; i < word.Length; i++) {
string prev = word.Substring(0, i) + word.Substring(i + 1);
if (dp.ContainsKey(prev)) {
dp[word] = Math.Max(dp[word], dp[prev] + 1);
}
}
maxLen = Math.Max(maxLen, dp[word]);
}
return maxLen;
}
public static void Main(string[] args) {
Solution solution = new Solution();
string[] words = new [] {"a", "b", "ba", "bca", "bda", "bdca"};
Console.WriteLine(solution.LongestStrChain(words));
}
}Graph vertices in this C# solution represent individual words, and directed edges indicate a predecessor relationship. Finding the longest path effectively implies the chain solution.