Longest String Chain — LeetCode 1048 Python Solution

MediumArrayHash TableTwo PointersStringDynamic ProgrammingSorting
Problem
#1048
Reading time
4 min

The problem

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.

Example

Input
words = ["a","b","ba","bca","bda","bdca"]
Output
4
Explanation
One of the longest word chains is ["a","ba","bda","bdca"].

Python solution

Python
class Solution:
    def longestStrChain(self, words: List[str]) -> int:
        def check(w1, w2):
            if len(w2) - len(w1) != 1:
                return False
            i = j = cnt = 0
            while i < len(w1) and j < len(w2):
                if w1[i] != w2[j]:
                    cnt += 1
                else:
                    i += 1
                j += 1
            return cnt < 2 and i == len(w1)

        n = len(words)
        dp = [1] * (n + 1)
        words.sort(key=lambda x: len(x))
        res = 1
        for i in range(1, n):
            for j in range(i):
                if check(words[j], words[i]):
                    dp[i] = max(dp[i], dp[j] + 1)
            res = max(res, dp[i])
        return res

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 1048. Longest String Chain is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1048. Longest String Chain?
LeetCode 1048. Longest String Chain is rated Medium on LeetCode.
What is the time complexity of LeetCode 1048. Longest String Chain?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1048. Longest String Chain?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1048. Longest String Chain cover?
LeetCode 1048. Longest String Chain is tagged Array, Hash Table, Two Pointers, String, Dynamic Programming and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview