LeetMotion
Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.
A subsequence is a string derived from another string by deleting some (or no) characters without changing the relative order of the remaining characters.
A common subsequence is a subsequence that appears in both strings.
At each pair of indices (i, j) in the two strings, there are two choices:
text1[i] == text2[j], this character is part of the LCS — take it and recurse on (i+1, j+1).max(lcs(i+1, j), lcs(i, j+1)).Why convert to bottom-up: Recursion has call-stack overhead and cache misses. Bottom-up DP fills the table row by row — no recursion, same O(n·m) time and space.
def longestCommonSubsequence(text1, text2): memo = {} def dfs(i, j): if i == len(text1) or j == len(text2): return 0 if (i, j) in memo: return memo[(i, j)] if text1[i] == text2[j]: memo[(i, j)] = 1 + dfs(i+1, j+1) else: memo[(i, j)] = max(dfs(i+1, j), dfs(i, j+1)) return memo[(i, j)] return dfs(0, 0)
Build a 2D table where dp[i][j] = LCS length of text1[0..i-1] and text2[0..j-1]. Row and column 0 are base cases (empty string), always 0.
text1[i-1] == text2[j-1]: extend the diagonal. dp[i][j] = 1 + dp[i-1][j-1].dp[i][j] = max(dp[i-1][j], dp[i][j-1]).dp[n][m].
Discussion
…