Java String Program · S55
Longest Common Subsequence in Java
A common subsequence keeps the order of characters in both strings but may skip some. The LCS table builds the answer from the answers for shorter prefixes.
Problem Statement
Given two strings, return the length of their longest common subsequence: the longest sequence of characters that appears in both strings in the same order, not necessarily next to each other.
If the strings share no characters, the answer is 0.
Input/Output Examples
"stone", "longest"Output3Explanation: "one" appears in order in both strings."abcb", "bcb"Output3Explanation: "bcb" is a subsequence of abcb."abc", "def"Output0Explanation: no character appears in both.Visual Explanation
| a \ b | ∅ | b | c | b |
|---|---|---|---|---|
| ∅ | 0 | 0 | 0 | 0 |
| a | 0 | 0 | 0 | 0 |
| b | 0 | 1 | 1 | 1 |
| c | 0 | 1 | 2 | 2 |
| b | 0 | 1 | 2 | 3 |
"abcb" and "bcb": each match (amber) adds 1 to the value on its upper-left diagonal. The answer, 3, is in the bottom-right cell (purple).When the last characters of two prefixes match, they can extend the best common subsequence of the shorter prefixes. When they do not, the best answer comes from dropping one of the two characters.
Approaches
Both approaches use the same recurrence. One fills the table iteratively; the other recurses with a cache.
Approach 1: Bottom-Up DP Table (Recommended)
Idea: dp[i][j] is the LCS length of the first i characters of a and the first j of b.
- Row 0 and column 0 stay 0 (an empty prefix).
- If
a[i - 1] == b[j - 1], setdp[i][j] = dp[i - 1][j - 1] + 1. - Otherwise, set
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]). - Return
dp[n][m].
Time: O(n × m) · Space: O(n × m).
Approach 2: Top-Down Memoised Recursion
Idea: compare the first characters of two suffixes: on a match, take 1 plus the rest; otherwise take the better of skipping either character, caching each result.
- If either suffix is empty, return 0.
- Return the cached value if present.
- Apply the match or skip rule and cache the result.
Time: O(n × m) · Space: O(n × m). Plus recursion depth up to n + m.
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Bottom-Up DP Table (Recommended)
Java initialises int arrays to 0, so the empty-prefix row and column need no code.
public class LcsTable {
// dp[i][j] = LCS length of the first i chars of a and the first j chars of b
static int lcs(String a, String b) {
int[][] dp = new int[a.length() + 1][b.length() + 1];
for (int i = 1; i <= a.length(); i++) {
for (int j = 1; j <= b.length(); 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]);
}
}
return dp[a.length()][b.length()];
}
public static void main(String[] args) {
String[][] cases = {{"stone", "longest"}, {"abcb", "bcb"}, {"abc", "def"}};
for (String[] c : cases) {
System.out.println("\"" + c[0] + "\", \"" + c[1] + "\" -> " + lcs(c[0], c[1]));
}
}
}
"stone", "longest" -> 3 "abcb", "bcb" -> 3 "abc", "def" -> 0
Time complexity: O(n × m) · Space complexity: O(n × m).
Approach 2: Top-Down Memoised Recursion
Only the states that are actually needed are computed.
import java.util.Arrays;
public class LcsMemo {
// Top-down recursion over suffixes, with every answer cached
static int lcs(String a, String b) {
int[][] memo = new int[a.length()][b.length()];
for (int[] row : memo) {
Arrays.fill(row, -1);
}
return solve(a, b, 0, 0, memo);
}
private static int solve(String a, String b, int i, int j, int[][] memo) {
if (i == a.length() || j == b.length()) {
return 0;
}
if (memo[i][j] >= 0) {
return memo[i][j];
}
int result = a.charAt(i) == b.charAt(j)
? 1 + solve(a, b, i + 1, j + 1, memo)
: Math.max(solve(a, b, i + 1, j, memo), solve(a, b, i, j + 1, memo));
return memo[i][j] = result;
}
public static void main(String[] args) {
String[][] cases = {{"stone", "longest"}, {"abcb", "bcb"}, {"abc", "def"}};
for (String[] c : cases) {
System.out.println("\"" + c[0] + "\", \"" + c[1] + "\" -> " + lcs(c[0], c[1]));
}
}
}
"stone", "longest" -> 3 "abcb", "bcb" -> 3 "abc", "def" -> 0
Time complexity: O(n × m) · Space complexity: O(n × m).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Bottom-Up DP Table | O(n × m) | O(n × m) |
| Top-Down Memoised Recursion | O(n × m) | O(n × m) |
Here n and m are the lengths of the strings. Each of the n × m states is computed once in constant time.
Interview Tips and Recommended Approach
- Separate subsequence from substring. The longest common substring needs a different recurrence that resets to 0 on a mismatch.
- Reconstruct the sequence if asked. Walk back from the bottom-right cell, following diagonal moves on matches.
- Save memory with two rows. Each row depends only on the row above.
- Know where it is used:
difftools and version control compare files with LCS-based algorithms.
Recommended Approach: Bottom-Up DP Table
Why: it is the textbook formulation, easy to trace by hand and straightforward to extend to reconstruct the subsequence itself.