
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.
1var longestStrChain = function(words) {
2 words.sort((a, b) => a.length - b.length);
3 const dp = new Map();
4 let maxLen = 1;
5
6 for (const word of words) {
7 dp.set(word, 1);
8 for (let i = 0; i < word.length; i++) {
9 const prev = word.slice(0, i) + word.slice(i + 1);
10 if (dp.has(prev)) {
11 dp.set(word, Math.max(dp.get(word), dp.get(prev) + 1));
12 }
13 }
14 maxLen = Math.max(maxLen, dp.get(word));
15 }
16
17 return maxLen;
18};
19
20console.log(longestStrChain(["a", "b", "ba", "bca", "bda", "bdca"]));This JavaScript approach uses a Map to keep the longest chain length for each word. Words are sorted by length, and for each word, predecessors are found by removal of characters considered.
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.
1
The Python solution leverages hash maps and substrings to simulate graph edges. Here, the graph's longest path is sought by comparing word predecessors, leveraging inherent string manipulations.