Skip to content

Commit b3c4afb

Browse files
committed
solve: longestCommonSubsequence
1 parent 3689422 commit b3c4afb

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

longest-common-subsequence/yolophg.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Time Complexity: O(m * n) - each (i, j) pair is computed once and stored, reducing redundant calls.
2+
# Space Complexity: O(m * n) - memoization dictionary stores O(m * n) states.
3+
# - Recursion stack depth is O(m + n) in the worst case.
4+
5+
class Solution:
6+
def longestCommonSubsequence(self, t1: str, t2: str) -> int:
7+
# to memoize results so we don't recompute the same subproblems
8+
m = dict()
9+
10+
# recursive function to compute LCS
11+
def s(i, j):
12+
# base case: if we reach the end of either string, there's nothing left to compare
13+
if i == len(t1) or j == len(t2):
14+
return 0
15+
16+
# if already computed this state, just return the cached value
17+
if (i, j) in m:
18+
return m[(i, j)]
19+
20+
# if the characters match, we take this character and move diagonally
21+
if t1[i] == t2[j]:
22+
m[i, j] = 1 + s(i + 1, j + 1)
23+
else:
24+
# if they don't match, we either move forward in t1 or t2 and take the max
25+
m[i, j] = max(s(i + 1, j), s(i, j + 1))
26+
27+
return m[i, j]
28+
29+
return s(0, 0)

0 commit comments

Comments
 (0)