InferenceAI

Enter at least two characters to search.

Start free

Longest Common Subsequence

mediumDynamic Programming25 min25 XP

Return the length of the longest subsequence (not necessarily contiguous) common to a and b.

dp[i][j]={dp[i−1][j−1]+1ai=bjmax⁡(dp[i−1][j],  dp[i][j−1])otherwisedp[i][j] = \begin{cases} dp[i-1][j-1] + 1 & a_i = b_j \\ \max(dp[i-1][j],\; dp[i][j-1]) & \text{otherwise} \end{cases}

Examples

EXAMPLE WALKTHROUGHthree letters

A guided view of the published example, not a trace of your code.

INPUT["abcde","ace"]
TASKlongest_common_subsequence()
EXPECTED OUTPUT3

Start with the input values shown in this example.

Example 1 of 3

Input: a = "abcde", b = "ace"

Output: 3

Explanation: three letters

Input: a = "abc", b = "abc"

Output: 3

Explanation: identical

Input: a = "abc", b = "def"

Output: 0

Explanation: nothing shared

Hint 1

Fill a (len(a) + 1) x (len(b) + 1) table row by row.

Topics

DSADynamic ProgrammingPython