#1048
Longest String Chain
MediumArrayHash TableTwo PointersStringDynamic ProgrammingSortingHash MapDynamic ProgrammingSorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * m) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n * m)Space O(n)
The optimal solution uses dynamic programming to build the longest chain by processing words in order of their lengths. By checking if a word can be formed by removing a character from a longer word, we can efficiently calculate the longest chain.
⚙️
Algorithm
3 steps- 1Step 1: Sort the words by their lengths.
- 2Step 2: Use a dictionary to store the maximum chain length for each word.
- 3Step 3: For each word, check all possible predecessors (words with one character removed) and update their chain lengths.
solution.py12 lines
1def longestStrChain(words):
2 words.sort(key=len)
3 dp = {}
4 max_length = 1
5 for word in words:
6 dp[word] = 1
7 for i in range(len(word)):
8 predecessor = word[:i] + word[i+1:]
9 if predecessor in dp:
10 dp[word] = max(dp[word], dp[predecessor] + 1)
11 max_length = max(max_length, dp[word])
12 return max_lengthℹ
Complexity note: The time complexity is O(n * m) where n is the number of words and m is the average length of the words, due to the sorting and the nested loop for checking predecessors. The space complexity is O(n) because we store the maximum chain lengths in a dictionary.
- 1The relationship between words can be visualized as a directed graph where edges represent valid predecessor relationships.
- 2Sorting words by length allows us to build chains incrementally, ensuring we only check valid predecessors.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.