Sign up to mark as complete
Sign up to bookmark this question
Longest Common Subsequence (LCS)
You're given two sequences of integers. Your task is to write a function that finds the Longest Common Subsequence (LCS) of the two sequences.
Inputs
Return a list of integers representing the Longest Common Subsequence of seq1 and seq2.
Example
Given the sequences seq1 = [1, 2, 3, 4, 5] and seq2 = [6, 7, 1, 2, 8], your function should return [1, 2].
def find_lcs(seq1: list, seq2: list) -> list:
pass
Inputs
- seq1: A list of integers representing the first sequence.
- seq2: A list of integers representing the second sequence.
Return a list of integers representing the Longest Common Subsequence of seq1 and seq2.
Example
Given the sequences seq1 = [1, 2, 3, 4, 5] and seq2 = [6, 7, 1, 2, 8], your function should return [1, 2].
# Implementing the Longest Common Subsequence (LCS) using Dynamic Programming
def find_lcs(seq1, seq2):
n = len(seq1)
m = len(seq2)
# Initialize a DP table with zeros
dp = [[0] * (m + 1) for _ in range(n + 1)]
# DP step: fill in the table
for i in range(1, n + 1):
for j in range(1, m + 1):
if seq1[i-1] == seq2[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
lcs = []
i, j = n, m
while i > 0 and j > 0:
if seq1[i-1] == seq2[j-1]:
lcs.append(seq1[i-1])
i -= 1
j -= 1
elif dp[i-1][j] > dp[i][j-1]:
i -= 1
else:
j -= 1
return lcs[::-1] # Reverse the LCS to get it in the correct order
# Test the function
seq1 = [1, 2, 3, 4, 5]
seq2 = [6, 7, 1, 2, 8]
print(find_lcs(seq1, seq2)) # Should return [1, 2]
Related Questions
| Title | Category | Subcategory | Difficulty | Status |
|---|---|---|---|---|
| All Pairs | Programming | Array and List Processing | Easy | Example |
| Arithmetic Mean | Programming | Array and List Processing | Hard | |
| Binary Search Tree (BST) | Programming | Array and List Processing | Hard | |
| Find the Missing Number | Programming | Array and List Processing | Easy | |
| Finding the Largest Possible Number | Programming | Array and List Processing | Easy | |
| Sorting Without Sort() | Programming | Array and List Processing | Hard | |
| Subarray Sum Equals Zero | Programming | Array and List Processing | Medium | |
| Sudoku | Programming | Array and List Processing | Hard |
Discussion
(1)
Please log in to see the discussion.
