1. Understand the Goal: The user wants an implementation of the Longest Common Subsequence (LCS) algorithm.
-
Identify the Core Concepts:
- Problem: Given two sequences (strings, arrays, etc.), find the length of the longest subsequence present in both of them. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguously.
- Algorithm: Dynamic Programming is the standard efficient approach (O(m⋅n)).
- Output: Usually, people want both the length and the actual string/sequence. I should provide both.
-
Determine the Approach:
- Naive Recursive: Exponential time (O(2n)). Too slow for anything but tiny inputs.
- Memoization (Top-Down): Stores results of subproblems. Good, but recursion depth can be an issue for very long strings.
- Tabulation (Bottom-Up): Iterative approach using a 2D table (matrix). This is the standard way to teach and implement LCS.
-
Drafting the Algorithm (Tabulation):
- Let string X have length m and string Y have length n.
- Create a table
dp of size (m+ initialized to 0.
-
Backtracking to find the String:
- Start at
dp[m][n].
- While i>0 and j>0:
- If X[i−1]==: This character is part of LCS. Add to result, move diagonally up-left ().
-
Selecting the Language: Python is the most readable and widely used for algorithmic demonstrations. I will also provide a C++ or Java example if requested, but Python is the safest default. I'll stick to Python for clarity, maybe adding C++ as an alternative if I feel generous, but usually, one solid implementation is better. Let's stick to Python.
-
Refining the Implementation:
- Function signature:
longest_common_subsequence(str1, str2)
- Edge cases: Empty strings (should return 0 or empty string).
- Readability: Add comments explaining the DP table and the backtracking logic.
-
Structuring the Response:
- Brief Explanation: What is LCS? What is the logic (DP)?
- Python Implementation: The code (Length calculation + String reconstruction).
- Example Usage: Show it working.
- Complexity Analysis: Time and Space complexity.
-
Self-Correction/Refinement during drafting:
- Initial thought: Just give the code.
- Correction: The user might need to understand how to get the string, not just the length. I must include the backtracking step.
- Memory Optimization: A standard O(m⋅n) space solution is easiest to understand. Space-optimized O(min(m,n)) is possible but makes code harder to read for a learner. I will present the standard 2D array approach.
-
Writing the Code (Mental Check):
def lcs(X, Y):
m, n = len(X), len(Y)
dp = [[0] * (n + 1) for _ in range(m + 1)]
# Fill table... (logic from step 4)
# Backtrack... (logic from step 5)
return lcs_string
-
Final Polish: Ensure variable names are meaningful (S1,S2 or text1, text2). Make sure to handle the index offset (strings are 0-indexed, DP table is 1-indexed logically).
-
Constructing Final Output: (This matches the provided good response).
- Introduction.
- Python Code.
- Explanation of the steps.
- Complexity.
Here is an implementation of the Longest Common Subsequence (LCS) algorithm.
This solution uses Dynamic Programming. It not only calculates the length of the subsequence but also reconstructs the actual string.
Python Implementation
def get_longest_common_subsequence(s1, s2):
m = len(s1)
n = len(s2)
# 1. Initialize a DP table with zeros
# The dimensions are (m+1) x (n+1) to handle empty string base cases
dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
# 2. Build the DP table (Find the length)
for i in range(1, m + 1):
for j in range(1, n + 1):
if s1[i - 1] == s2[j - 1]:
# If characters match, extend the length from the diagonal
dp[i][j] = dp[i - 1][j - 1] + 1
else:
# If they don't match, take the max value from left or top
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
# The length of the LCS is now stored in dp[m][n]
# 3. Reconstruct the String (Backtracking)
# Start from the bottom-right corner of the table
i, j = m, n
lcs_result = []
while i > 0 and j > 0:
# If current characters match, this character is part of LCS
if s1[i - 1] == s2[j - 1]:
lcs_result.append(s1[i - 1])
i -= 1
j -= 1
# If not, move in the direction of the greater value
elif dp[i - 1][j] > dp[i][j - 1]:
i -= 1
else:
j -= 1
# The string was built backwards, so reverse it
return "".join(reversed(lcs_result))
# --- Example Usage ---
string_1 = "AGGTAB"
string_2 = "GXTXAYB"
lcs = get_longest_common_subsequence(string_1, string_2)
print(f"String 1: {string_1}")
print(f"String 2: {string_2}")
print(f"LCS: {lcs}")
print(f"Length: {len(lcs)}")
How It Works
- Grid Initialization: We create a 2D grid (table) where
dp[i][j] represents the length of the LCS between the first i characters of s1 and the first j characters of s2.
- Filling the Table: We iterate through the table:
- Match: If
s1 and s2 have the same character at the current position, we add 1 to the result found in the top-left diagonal cell.
- No Match: If they differ, the value is simply the maximum of the cell directly above or directly to the left.
- Reconstruction: Once the table is full, the bottom-right cell contains the length of the LCS. To get the actual string, we backtrack from that corner:
- If characters matched at that step, we add the character to our result and move diagonally up-left.
- If they didn't match, we move towards the cell (up or left) that had the higher value.
Complexity Analysis
- Time Complexity: O(m×n), where m and n are the lengths of the two strings. We must fill every cell in the table.
- Space Complexity: O(m× to store the DP table. (Note: If you only need the and not the string itself, this can be optimized to space).