Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Length of the longest common subsequence of THREE strings (3-D DP).

Problem: Length of the longest common subsequence of THREE strings (3-D DP).
def lcs3(a, b, c):
    dp = [[[0] * (len(c) + 1) for _ in range(len(b) + 1)] for _ in range(len(a) + 1)]
    for i in range(1, len(a) + 1):
        for j in range(1, len(b) + 1):
            for k in range(1, len(c) + 1):
                if a[i-1] == b[j-1] == c[k-1]: dp[i][j][k] = dp[i-1][j-1][k-1] + 1
                else: dp[i][j][k] = max(dp[i-1][j][k], dp[i][j-1][k], dp[i][j][k-1])
    return dp[-1][-1][-1]
print(lcs3("algorithm", "logarithm", "rhythm"))
What is printed?
  1. A. 4
  2. B. 5
  3. C. 6
  4. D. 3

Correct answer: A. 4

Pairwise LCS values do not combine: LCS(algorithm, logarithm) is long, but the third string 'rhythm' limits what all three share. Common to all three in order is 'rthm' (r, t, h, m) → 4. The 3-D table costs O(|a|·|b|·|c|).

More Coding Interview Problems questions

Exams that ask this topic