CodeArchon

medium2-D Dynamic ProgrammingMicrosoftAmazon

Shared Script Finder

A DNA analyst finds the longest common ordered match between two strands (letters need not be contiguous).

Given two strings, return the length of their longest common subsequence (not substring).

Choose approach

0
0
0
0
0
1
cur
?
?
0
?
?
?
0
?
?
?
0
?
?
?
0
?
?
?
1/15
Narrationstep 1 of 15

(a vs a) ✓ match → dp[1][1] = 1.

1def longestCommonSubsequence(a, b):
2 m, n = len(a), len(b)
3 dp = [[0]*(n+1) for _ in range(m+1)]
4 for i in range(1, m+1):
5 for j in range(1, n+1):
6 dp[i][j] = dp[i-1][j-1] + 1 if a[i-1] == b[j-1] else max(dp[i-1][j], dp[i][j-1])
7 return dp[m][n]
Variables
i=1
j=1
char1=a
char2=a
value=1

How to think about it

  1. Diagonal transition on match; L-shape max on mismatch.
  2. Reconstruct via backtrack from dp[m][n].

Edge cases to catch in interview

  • Empty string -> 0.
  • Identical strings -> length.

Examples

Example 10
{"text1":"abc","text2":"def"}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed