Longest Common Subsequence (LCS)

Sign up to mark as complete Sign up to bookmark this question
Asset Pricingx / 34
Behavioral Questionsx / 7
Brain Teasersx / 76
Derivatives Theoryx / 108
Digital Assets - Cryptox / 64
Energy Tradingx / 40
Linear Algebrax / 24
Math Questionsx / 45
Probability and Statisticsx / 169
Programmingx / 35
Totalx / 602

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.
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.
Output
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]
Title Category Subcategory Difficulty Status
All Pairs ProgrammingArray and List ProcessingEasy
Example
Arithmetic Mean ProgrammingArray and List ProcessingHard
Binary Search Tree (BST) ProgrammingArray and List ProcessingHard
Find the Missing Number ProgrammingArray and List ProcessingEasy
Finding the Largest Possible Number ProgrammingArray and List ProcessingEasy
Sorting Without Sort() ProgrammingArray and List ProcessingHard
Subarray Sum Equals Zero ProgrammingArray and List ProcessingMedium
Sudoku ProgrammingArray and List ProcessingHard

Please log in to see the discussion.