DevPath

← All problems

Longest Common Subsequence

Medium dynamic-programming · strings

Description

Return the length of the longest subsequence common to both strings.

Constraints

0 <= lengths <= 1000

Examples

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

Output: 3

Hints (1)
  • On a match add one to the diagonal; otherwise take the best of the two neighbours.

Solutions

Rolling DP row. · Time O(n*m) · Space O(m)

func longestCommonSubsequence(a, b string) int {
    n, m := len(a), len(b)
    dp := make([]int, m+1)
    for i := 1; i <= n; i++ {
        prev := 0
        for j := 1; j <= m; j++ {
            tmp := dp[j]
            if a[i-1] == b[j-1] {
                dp[j] = prev + 1
            } else if dp[j] < dp[j-1] {
                dp[j] = dp[j-1]
            }
            prev = tmp
        }
    }
    return dp[m]
}

Create a free account to submit solutions, track progress and save problems.

Create account