Tech Interview RoomStudy guides

Dynamic Programming

Longest common subsequence. Compare recursion, memoisation, a 2D table and a rolling 1D array.

Advanced · 2 min read · Lesson 5 of 6 in Dynamic Programming

Problem

"abcde" and "ace" → 3 ("ace"). Characters keep their order but need not be contiguous.

Pattern

2D DP on two sequences: dp[i][j] = answer for prefixes a[0..i) and b[0..j); if the last characters match, extend the diagonal; otherwise take the better of dropping one character from either string.

Approach 1: Plain recursion (feasible, O(2^(m+n)))

java
class LcsRecursive {
    static int lcs(String a, String b) { return go(a, b, a.length(), b.length()); }
    private static int go(String a, String b, int i, int j) {
        if (i == 0 || j == 0) return 0;
        if (a.charAt(i - 1) == b.charAt(j - 1)) return 1 + go(a, b, i - 1, j - 1);
        return Math.max(go(a, b, i - 1, j), go(a, b, i, j - 1));
    }
}

Approach 2: Memoisation (O(m·n) time and space)

java
import java.util.Arrays;

class LcsMemo {
    static int lcs(String a, String b) {
        int[][] memo = new int[a.length() + 1][b.length() + 1];
        for (int[] row : memo) Arrays.fill(row, -1);
        return go(a, b, a.length(), b.length(), memo);
    }
    private static int go(String a, String b, int i, int j, int[][] memo) {
        if (i == 0 || j == 0) return 0;
        if (memo[i][j] != -1) return memo[i][j];
        int r = a.charAt(i - 1) == b.charAt(j - 1) ? 1 + go(a, b, i - 1, j - 1, memo)
                                                   : Math.max(go(a, b, i - 1, j, memo), go(a, b, i, j - 1, memo));
        return memo[i][j] = r;
    }
}

Approach 3: Bottom-up table, also reconstructing the subsequence (O(m·n))

java
class LcsTable {
    static String lcsString(String a, String b) {
        int m = a.length(), n = b.length();
        int[][] dp = new int[m + 1][n + 1];
        for (int i = 1; i <= m; i++)
            for (int j = 1; j <= n; j++)
                dp[i][j] = a.charAt(i - 1) == b.charAt(j - 1) ? dp[i - 1][j - 1] + 1 : Math.max(dp[i - 1][j], dp[i][j - 1]);
        StringBuilder sb = new StringBuilder();                  // walk back from the corner
        for (int i = m, j = n; i > 0 && j > 0; ) {
            if (a.charAt(i - 1) == b.charAt(j - 1)) { sb.append(a.charAt(i - 1)); i--; j--; }
            else if (dp[i - 1][j] >= dp[i][j - 1]) i--; else j--;
        }
        return sb.reverse().toString();
    }
}

Approach 4: Rolling 1D array (O(m·n) time, O(min(m, n)) space) — optimal for length only

java
class LcsRolling {
    static int lcs(String a, String b) {
        if (b.length() > a.length()) { String t = a; a = b; b = t; }   // keep the row short
        int[] dp = new int[b.length() + 1];
        for (int i = 1; i <= a.length(); i++) {
            int diag = 0;                                        // dp[i-1][j-1]
            for (int j = 1; j <= b.length(); j++) {
                int up = dp[j];
                dp[j] = a.charAt(i - 1) == b.charAt(j - 1) ? diag + 1 : Math.max(dp[j], dp[j - 1]);
                diag = up;
            }
        }
        return dp[b.length()];
    }
}

class LcsDemo {
    public static void main(String[] args) {
        System.out.println(LcsRecursive.lcs("abcde", "ace") + " " + LcsMemo.lcs("abcde", "ace") + " "
            + LcsTable.lcsString("abcde", "ace") + " " + LcsRolling.lcs("abcde", "ace"));   // 3 3 ace 3
        System.out.println(LcsRolling.lcs("AGGTAB", "GXTXAYB") + " " + LcsTable.lcsString("AGGTAB", "GXTXAYB"));   // 4 GTAB
    }
}

Feasible → optimal

Exponential recursion → O(m·n) memo or table (O(m·n) space, needed to reconstruct the subsequence) → O(m·n) time with O(min(m, n)) space for the length only.

Follow-up questions interviewers ask

Try answering each one before you open it.

Related (same pattern): edit distance (Levenshtein).

dp[i][j] = a[i-1] == b[j-1] ? dp[i-1][j-1] : 1 + min(dp[i-1][j] (delete), dp[i][j-1] (insert), dp[i-1][j-1] (replace)). Same table and the same rolling-array optimisation.

Related (same pattern): longest palindromic subsequence, and shortest common supersequence.

Longest palindromic subsequence = LCS of the string and its reverse. Shortest common supersequence length = m + n - LCS. Minimum deletions to make two strings equal = m + n - 2 × LCS.