LeetCode 1143: Longest Common Subsequence — Step-by-Step Visual Trace

Published: (April 9, 2026 at 02:37 AM EDT)
2 min read
Source: Dev.to

Source: Dev.to

Problem Overview

Find the length of the longest common subsequence (LCS) between two strings, where a subsequence maintains the relative order of characters but doesn’t need to be contiguous.

Approach

Use dynamic programming with a 2D table where dp[i][j] represents the LCS length of the first i characters of text1 and the first j characters of text2.

  • If the characters match, add 1 to the diagonal value.
  • Otherwise, take the maximum of the left or top cell.

Complexity

  • Time: O(m·n)
  • Space: O(m·n)

Solution (Python)

class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        m, n = len(text1), len(text2)

        # Create a 2D dp array of size (m+1) x (n+1) and initialize it with zeros.
        dp = [[0] * (n + 1) for _ in range(m + 1)]

        # Fill in the dp array using dynamic programming.
        for i in range(1, m + 1):
            for j in range(1, n + 1):
                if text1[i - 1] == text2[j - 1]:
                    dp[i][j] = dp[i - 1][j - 1] + 1
                else:
                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])

        # The value in dp[m][n] represents the length of the LCS.
        return dp[m][n]

Try it yourself: open TraceLit and step through every line.

0 views
Back to Blog

Related posts

Read more »