Java String Program · S66
Count Distinct Subsequences in Java
In how many ways can you delete characters from s to leave exactly t? Each character of s is either skipped or used for the next character of t.
Problem Statement
Given strings s and t, return how many different ways t can be formed as a subsequence of s. Two ways are different if they use different positions of s.
The empty string t can be formed in exactly one way. Counts can grow quickly, so they are kept in a long.
Input/Output Examples
s = "banana", t = "ban"Output3Explanation: b with (a, n) at positions (1, 2), (1, 4) or (3, 4).s = "aabb", t = "ab"Output4Explanation: each of the two a's pairs with each of the two b's.s = "abc", t = "abcd"Output0Explanation: t is longer than s.Visual Explanation
| s \ t | ∅ | b | a | n |
|---|---|---|---|---|
| ∅ | 1 | 0 | 0 | 0 |
| b | 1 | 1 | 0 | 0 |
| a | 1 | 1 | 1 | 0 |
| n | 1 | 1 | 1 | 1 |
| a | 1 | 1 | 2 | 1 |
| n | 1 | 1 | 2 | 3 |
| a | 1 | 1 | 3 | 3 |
s = "banana" and t = "ban": each cell counts the ways to form a prefix of t from a prefix of s. The count for "ban" grows at each n (amber) and ends at 3 (purple).Every character of s can always be skipped, which carries the count down. When it equals the next character of t, it can also be used, which adds the count from the diagonal.
Approaches
Both approaches use the skip-or-use recurrence. The first stores the whole table; the second keeps a single row.
Approach 1: 1D DP, Updated Backwards (Recommended)
Idea: ways[j] counts the ways to form t[0..j) from the characters read so far; for each new character, update j from high to low.
- Set
ways[0] = 1. - For each character of
s, loopjfromt.length()down to 1. - If
s[i] == t[j - 1], addways[j - 1]toways[j]. - Return
ways[m].
Time: O(n × m) · Space: O(m).
Approach 2: 2D DP Table
Idea: dp[i][j] is the number of ways to form t[0..j) from s[0..i).
- Set
dp[i][0] = 1for everyi. dp[i][j] = dp[i - 1][j](skips[i - 1]).- If
s[i - 1] == t[j - 1], also adddp[i - 1][j - 1](use it). - Return
dp[n][m].
Time: O(n × m) · Space: O(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: 1D DP, Updated Backwards (Recommended)
Going backwards makes sure each character of s is used at most once in each way.
public class DistinctSubseq1D {
// ways[j] = number of ways to form t[0..j) from the characters read so far
static long countWays(String s, String t) {
long[] ways = new long[t.length() + 1];
ways[0] = 1; // the empty prefix of t: one way
for (int i = 0; i < s.length(); i++) {
for (int j = t.length(); j >= 1; j--) { // backwards, so each s[i] is used once
if (s.charAt(i) == t.charAt(j - 1)) {
ways[j] += ways[j - 1];
}
}
}
return ways[t.length()];
}
public static void main(String[] args) {
String[][] cases = {{"banana", "ban"}, {"aabb", "ab"}, {"abc", "abcd"}};
for (String[] c : cases) {
System.out.println("s=\"" + c[0] + "\", t=\"" + c[1] + "\" -> " + countWays(c[0], c[1]));
}
}
}
s="banana", t="ban" -> 3 s="aabb", t="ab" -> 4 s="abc", t="abcd" -> 0
Time complexity: O(n × m) · Space complexity: O(m).
Approach 2: 2D DP Table
The full table makes the recurrence easy to see and to debug.
public class DistinctSubseq2D {
// dp[i][j] = ways to form t[0..j) as a subsequence of s[0..i)
static long countWays(String s, String t) {
int n = s.length();
int m = t.length();
long[][] dp = new long[n + 1][m + 1];
for (int i = 0; i <= n; i++) {
dp[i][0] = 1;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
dp[i][j] = dp[i - 1][j]; // skip s[i - 1]
if (s.charAt(i - 1) == t.charAt(j - 1)) {
dp[i][j] += dp[i - 1][j - 1]; // or use it for t[j - 1]
}
}
}
return dp[n][m];
}
public static void main(String[] args) {
String[][] cases = {{"banana", "ban"}, {"aabb", "ab"}, {"abc", "abcd"}};
for (String[] c : cases) {
System.out.println("s=\"" + c[0] + "\", t=\"" + c[1] + "\" -> " + countWays(c[0], c[1]));
}
}
}
s="banana", t="ban" -> 3 s="aabb", t="ab" -> 4 s="abc", t="abcd" -> 0
Time complexity: O(n × m) · Space complexity: O(n × m).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| 1D DP, Updated Backwards | O(n × m) | O(m) |
| 2D DP Table | O(n × m) | O(n × m) |
Here n is the length of s and m the length of t. Both approaches compute n × m values; the 1D version keeps only m + 1 of them.
Interview Tips and Recommended Approach
- Initialise the empty target. There is exactly one way to form
"", which is what seeds every count. - Use
long. The number of ways grows combinatorially and can overflow anint. - Explain the backward loop. A forward loop would let one character of
scount twice. - Relate it to LCS. Both tables walk two prefixes; here you count ways instead of measuring length.
Recommended Approach: 1D DP, Updated Backwards
Why: it needs only one array of length m + 1 and one simple update rule, and the backward loop is a reusable trick for knapsack-style counting.