Skip to content

Create lcs_algorithm.py #11887

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions lcs_algorithm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
def longest_common_subsequence(X, Y):

Check failure on line 1 in lcs_algorithm.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (N803)

lcs_algorithm.py:1:32: N803 Argument name `X` should be lowercase

Check failure on line 1 in lcs_algorithm.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (N803)

lcs_algorithm.py:1:35: N803 Argument name `Y` should be lowercase
"""
Find the longest common subsequence (LCS) between two strings.

Args:
X (str): First string
Y (str): Second string

Returns:
str: The longest common subsequence
"""
m = len(X)
n = len(Y)

# Create a 2D array to store the lengths of common subsequences
dp = [[0] * (n + 1) for _ in range(m + 1)]

# Fill the 2D array using dynamic programming
for i in range(1, m + 1):
for j in range(1, n + 1):
if X[i - 1] == Y[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])

# Reconstruct the LCS from the 2D array
lcs = []
i, j = m, n
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

# Return the LCS in the correct order
return "".join(reversed(lcs))


# Example usage:
X = "AGGTAB"
Y = "GXTXAYB"
lcs = longest_common_subsequence(X, Y)
print(f"The longest common subsequence is: {lcs}")
Loading