Skip to content

Commit 47335b2

Browse files
committed
Added Python solution for Longest Common Subsequence
1 parent c79034c commit 47335b2

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# longest_common_subsequence.py
2+
# This program finds the Longest Common Subsequence (LCS) between two strings
3+
# using Dynamic Programming and also prints the actual LCS string.
4+
5+
def longest_common_subsequence(x: str, y: str):
6+
m, n = len(x), len(y)
7+
dp = [[0] * (n + 1) for _ in range(m + 1)]
8+
9+
# Fill the dp table
10+
for i in range(1, m + 1):
11+
for j in range(1, n + 1):
12+
if x[i - 1] == y[j - 1]:
13+
dp[i][j] = 1 + dp[i - 1][j - 1]
14+
else:
15+
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
16+
17+
# Reconstruct the LCS string
18+
i, j = m, n
19+
lcs = []
20+
while i > 0 and j > 0:
21+
if x[i - 1] == y[j - 1]:
22+
lcs.append(x[i - 1])
23+
i -= 1
24+
j -= 1
25+
elif dp[i - 1][j] > dp[i][j - 1]:
26+
i -= 1
27+
else:
28+
j -= 1
29+
30+
lcs.reverse()
31+
lcs_str = ''.join(lcs)
32+
33+
# Print DP table (for visualization)
34+
print("DP Table:")
35+
for row in dp:
36+
print(row)
37+
38+
print(f"\nLength of LCS: {dp[m][n]}")
39+
print(f"LCS String: {lcs_str}")
40+
41+
return dp[m][n], lcs_str
42+
43+
44+
if __name__ == "__main__":
45+
s1 = input("Enter first string: ")
46+
s2 = input("Enter second string: ")
47+
longest_common_subsequence(s1, s2)

0 commit comments

Comments
 (0)