LCS (Longest Common Subsequence) of three strings
Pattern: Strings DP
The LCS idea in three dimensions: dp[i][j][k] for prefixes of all three strings. If all three last characters match, use the diagonal + 1; otherwise drop one character from any one string.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Return the length of the longest subsequence common to all three strings a, b and c.
Think first
- What changes from two strings?
- When can the last characters be used?
- How many ways to drop a character?
Hints
Brute force, and why it fails
Try every subsequence of one string: exponential.
The key insight
Prefixes of all three strings describe every subproblem.
Dry run
'geeks', 'geeksfor', 'geeksforgeeks'. All three start with 'geeks'.
Step 1 of 2
The plan
dp[i][j][k] = dp[i-1][j-1][k-1] + 1 if all equal else max(dp[i-1][j][k], dp[i][j-1][k], dp[i][j][k-1])
Complexity
- Time
O(m × n × p)- Space
O(m × n × p)
A 3D table.
Edge cases
- One empty string: 0.
- All equal.
- No common character.
I've built my logic, show the code
Java
class Solution {
public int LCSof3(String a, String b, String c) {
int x = a.length(), y = b.length(), z = c.length();
int[][][] dp = new int[x + 1][y + 1][z + 1]; // the LCS of the first i, j and k characters
for (int i = 1; i <= x; i++)
for (int j = 1; j <= y; j++)
for (int k = 1; k <= z; k++)
dp[i][j][k] = a.charAt(i - 1) == b.charAt(j - 1) && b.charAt(j - 1) == c.charAt(k - 1)
? dp[i - 1][j - 1][k - 1] + 1 // all three match
: Math.max(dp[i - 1][j][k], Math.max(dp[i][j - 1][k], dp[i][j][k - 1])); // drop one
return dp[x][y][z];
}
}C++
class Solution {
public:
int LCSof3(string a, string b, string c) {
int x = static_cast<int>(a.size()), y = static_cast<int>(b.size()), z = static_cast<int>(c.size());
vector<vector<vector<int>>> dp(x + 1, vector<vector<int>>(y + 1, vector<int>(z + 1, 0))); // first i, j, k chars
for (int i = 1; i <= x; i++)
for (int j = 1; j <= y; j++)
for (int k = 1; k <= z; k++)
dp[i][j][k] = a[i - 1] == b[j - 1] && b[j - 1] == c[k - 1]
? dp[i - 1][j - 1][k - 1] + 1 // all three match
: max(dp[i - 1][j][k], max(dp[i][j - 1][k], dp[i][j][k - 1])); // drop one
return dp[x][y][z];
}
};Python
class Solution:
def LCSof3(self, a: str, b: str, c: str) -> int:
x, y, z = len(a), len(b), len(c)
dp = [[[0] * (z + 1) for _ in range(y + 1)] for _ in range(x + 1)] # the LCS of the first i, j, k characters
for i in range(1, x + 1):
for j in range(1, y + 1):
for k in range(1, z + 1):
if a[i - 1] == b[j - 1] == c[k - 1]:
dp[i][j][k] = dp[i - 1][j - 1][k - 1] + 1 # all three match
else:
dp[i][j][k] = max(dp[i - 1][j][k], dp[i][j - 1][k], dp[i][j][k - 1]) # drop one
return dp[x][y][z]Common mistakes
- Taking LCS of pairs, which can be too long.
- Off-by-one.