DDSA Solutions

Longest Common Subsequence

Time: O(n*m)
Space: O(n*m)
Advertisement

Intuition

dp[i][j] = LCS length of s1[0..i-1] and s2[0..j-1]. If chars match: dp[i][j]=dp[i-1][j-1]+1. Else: dp[i][j]=max(dp[i-1][j], dp[i][j-1]).

Algorithm

  1. 1dp[m+1][n+1], all 0.
  2. 2For i from 1 to m, j from 1 to n: if s1[i-1]==s2[j-1]: dp[i][j]=dp[i-1][j-1]+1. Else: dp[i][j]=max(dp[i-1][j],dp[i][j-1]).
  3. 3Return dp[m][n].

Example Walkthrough

Input: s1="ABCBDAB", s2="BDCAB"

  1. 1.LCS = "BCAB" or "BDAB" (length 4). dp[7][5]=4.

Output: 4

Common Pitfalls

  • LCS counts non-contiguous characters in order — not the same as Longest Common Substring.
Longest Common Subsequence.java
Java
// Approach: DP. dp[i][j] = LCS of s1[0..i-1] and s2[0..j-1]. Match: dp[i-1][j-1]+1; no match: max of skip either.
// Time: O(n*m) Space: O(n*m)
class Solution {
    static int lcs(String s1, String s2) {
        int n = s1.length();
        int m = s2.length();
        int[][] dp = new int[n + 1][m + 1];

        for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= m; j++) {
                if (i == 0 || j == 0)
                    dp[i][j] = 0;
                else if (s1.charAt(i - 1) == s2.charAt(j - 1))
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                else
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
            }
        }

        return dp[n][m];
    }
}
Advertisement
Was this solution helpful?