Solving Leetcode Interviews in Seconds with AI: Longest Common Subsequence
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1143" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. For example, "ace" is a subsequence of "abcde". A common subsequence of two strings is a subsequence that is common to both strings. Example 1: Input: text1 = "abcde", text2 = "ace" Output: 3 Explanation: The longest common subsequence is "ace" and its length is 3. Example 2: Input: text1 = "abc", text2 = "abc" Output: 3 Explanation: The longest common subsequence is "abc" and its length is 3. Example 3: Input: text1 = "abc", text2 = "def" Output: 0 Explanation: There is no such common subsequence, so the result is 0. Constraints: 1 <= text1.length, text2.length <= 1000 text1 and text2 consist of only lowercase English characters.
Explanation
Here's a breakdown of the approach, followed by the Python code:
- Dynamic Programming: Build a 2D table (DP table) where
dp[i][j]stores the length of the longest common subsequence oftext1[0...i-1]andtext2[0...j-1]. - Base Case: The first row and column of the DP table are initialized to 0, representing the case where one of the strings is empty.
Recursive Relation: If
text1[i-1]andtext2[j-1]are equal, thendp[i][j] = dp[i-1][j-1] + 1. Otherwise,dp[i][j] = max(dp[i-1][j], dp[i][j-1]).Runtime Complexity: O(m*n), where 'm' is the length of
text1and 'n' is the length oftext2.- Storage Complexity: O(m*n)
Code
def longestCommonSubsequence(text1: str, text2: str) -> int:
"""
Finds the length of the longest common subsequence of two strings.
Args:
text1: The first string.
text2: The second string.
Returns:
The length of the longest common subsequence.
"""
n = len(text1)
m = len(text2)
# Initialize a DP table to store lengths of LCS for subproblems
dp = [[0] * (m + 1) for _ in range(n + 1)]
# Iterate through the strings to populate the DP table
for i in range(1, n + 1):
for j in range(1, m + 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 bottom-right cell contains the length of the LCS of the entire strings
return dp[n][m]