Longest Common Subsequence — LeetCode 1143 Python Solution

MediumStringDynamic Programming
Problem
#1143
Reading time
2 min

The problem

Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.

Example

Input
text1 = "abcde", text2 = "ace"
Output
3
Explanation
The longest common subsequence is "ace" and its length is 3.

Python solution

Python
class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        m, n = len(text1), len(text2)
        f = [[0] * (n + 1) for _ in range(m + 1)]
        for i in range(1, m + 1):
            for j in range(1, n + 1):
                if text1[i - 1] == text2[j - 1]:
                    f[i][j] = f[i - 1][j - 1] + 1
                else:
                    f[i][j] = max(f[i - 1][j], f[i][j - 1])
        return f[m][n]

Complexity

MeasureComplexity
TimeO(m \times n)
SpaceO(m \times n) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1143. Longest Common Subsequence is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

On study lists

This problem is on Blind 75, NeetCode 150 and LeetCode 75.

Frequently asked questions

How hard is LeetCode 1143. Longest Common Subsequence?
LeetCode 1143. Longest Common Subsequence is rated Medium on LeetCode.
What is the time complexity of LeetCode 1143. Longest Common Subsequence?
The Python solution on this page runs in O(m \times n).
What is the space complexity of LeetCode 1143. Longest Common Subsequence?
The Python solution on this page uses O(m \times n) auxiliary space.
What topics does LeetCode 1143. Longest Common Subsequence cover?
LeetCode 1143. Longest Common Subsequence is tagged String and Dynamic Programming 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