From e7b53b41c27dc91eb41b8325da7a722f89a032be Mon Sep 17 00:00:00 2001 From: jaimin45-art Date: Fri, 17 Oct 2025 10:45:04 +0530 Subject: [PATCH 1/2] Added Longest Common Subsequence program in Python --- strings/add-longest-common-subsequence.py | 47 +++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 strings/add-longest-common-subsequence.py diff --git a/strings/add-longest-common-subsequence.py b/strings/add-longest-common-subsequence.py new file mode 100644 index 000000000000..a2d71fa223b4 --- /dev/null +++ b/strings/add-longest-common-subsequence.py @@ -0,0 +1,47 @@ +# longest_common_subsequence.py +# This program finds the Longest Common Subsequence (LCS) between two strings +# using Dynamic Programming and also prints the actual LCS string. + +def longest_common_subsequence(x: str, y: str): + m, n = len(x), len(y) + dp = [[0] * (n + 1) for _ in range(m + 1)] + + # Fill the dp table + for i in range(1, m + 1): + for j in range(1, n + 1): + if x[i - 1] == y[j - 1]: + dp[i][j] = 1 + dp[i - 1][j - 1] + else: + dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) + + # Reconstruct the LCS string + i, j = m, n + lcs = [] + while i > 0 and j > 0: + if x[i - 1] == y[j - 1]: + lcs.append(x[i - 1]) + i -= 1 + j -= 1 + elif dp[i - 1][j] > dp[i][j - 1]: + i -= 1 + else: + j -= 1 + + lcs.reverse() + lcs_str = ''.join(lcs) + + # Print DP table (for visualization) + print("DP Table:") + for row in dp: + print(row) + + print(f"\nLength of LCS: {dp[m][n]}") + print(f"LCS String: {lcs_str}") + + return dp[m][n], lcs_str + + +if __name__ == "__main__": + s1 = input("Enter first string: ") + s2 = input("Enter second string: ") + longest_common_subsequence(s1, s2) From 54da4a26d0d82b0237ffa8d8adfb0a55f250ae7a Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Fri, 17 Oct 2025 05:20:17 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- strings/add-longest-common-subsequence.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/strings/add-longest-common-subsequence.py b/strings/add-longest-common-subsequence.py index a2d71fa223b4..7f4569fdf33a 100644 --- a/strings/add-longest-common-subsequence.py +++ b/strings/add-longest-common-subsequence.py @@ -2,6 +2,7 @@ # This program finds the Longest Common Subsequence (LCS) between two strings # using Dynamic Programming and also prints the actual LCS string. + def longest_common_subsequence(x: str, y: str): m, n = len(x), len(y) dp = [[0] * (n + 1) for _ in range(m + 1)] @@ -28,7 +29,7 @@ def longest_common_subsequence(x: str, y: str): j -= 1 lcs.reverse() - lcs_str = ''.join(lcs) + lcs_str = "".join(lcs) # Print DP table (for visualization) print("DP Table:")