Distinct subsequences
Advanced · 11 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Distinct subsequences counts how many different ways a short pattern can be picked, in order, from a longer text. For each letter you either skip it or, if it matches the needed letter, use it, and add the two counts. It counts matches rather than just checking whether one exists.
Practical use cases
- Web app: Counting a pattern in event logs. A monitoring dashboard looks at a long log of events and counts how many times the sequence login, add-to-cart, pay appears in order, with other events allowed between. The count is found in a single pass of a table instead of trying every combination of log lines.
- Web app: Password-strength or pattern rules. A security page checks how many ways a short pattern, such as "abc", can be hidden inside a long passphrase. A high count shows that a weak passphrase contains many easy patterns by accident, which helps explain to users why length and variety matter.
- System: Genetics and pattern counting. Genetics tools count how many ways a short gene code can be found inside a long DNA strand. The count tells scientists how common the pattern is.
The story: Spelling ANA from a Banana Stall
Mira was selling tiles with letters at the fruit market: B A N A N A. Kabir challenged her: "Pick some tiles, keep their order, and spell ANA. How many different ways can you do it?" Mira found (A, N, A) using tiles 2, 3, 4. Then tiles 2, 3, 6. Then 2, 5, 6... the count kept growing and she kept losing count.
Her trick: look at only the last tile of the pile you currently have. You can always skip it, and then the number of ways is what you had without it. And if that tile matches the last letter you still need, you can also use it, which adds the ways to spell the shorter word from the shorter pile. Skip plus use: that is the whole rule.
Mira filled a table whose rows are "the first i tiles" and whose columns are "the first j letters of ANA". The first column is all 1s: spelling nothing is possible in exactly one way. The last cell said 4. This is the Distinct Subsequences counting problem, famous in interviews.
How to spot this problem, and where you need it
You need to count in how many different ways a short sequence can be found, in order, inside a longer one, and the count can be huge.
Signs you need it
- The problem says "number of distinct subsequences" or "how many ways can s produce t".
- Just checking if the pattern exists is easy, but you need the number of ways.
- A recursive attempt keeps recomputing the same positions of the text and pattern.
Where to use it in a project
- Counting ordered event patterns, such as user journeys, in long logs.
- Statistical checks of how often a sequence can appear in a long string or data stream.
The solution
Make a table with a row for each prefix of the pattern and a column for each prefix of the text. An empty pattern can be made in exactly one way. For each cell, the count is the count when the current text letter is skipped, plus, if that letter equals the current pattern letter, the count when both are stepped back. Fill row by row; the bottom-right cell is the answer.
Payoff: Before: enumerating every subsequence, over a trillion for a 40-letter text. After: a table of about 40 by 5 cells.
Explain it like I am 8
For each tile, you either leave it in the basket or use it. Leaving it keeps the same count of ways. Using it only counts if it is the letter you are looking for. You add both stories together and write the total in the grid.
How it works, step by step
- Rows are prefixes of the big word
s; columns are prefixes of the targett. - First column = 1 (one way to build the empty word). The first row after that is 0 (an empty pile cannot build a letter).
- Skip the letter: start with
dp[i][j] = dp[i-1][j]. - If s[i-1] equals t[j-1], also add
dp[i-1][j-1](use the letter). - The answer is
dp[m][n], the bottom-right cell. Use big numbers if the strings are long.
The code in four languages
PHP
<?php
// Count the ways string $t appears as a subsequence of string $s.
function numDistinct(string $s, string $t): int {
$m = strlen($s); $n = strlen($t);
$dp = array_fill(0, $m + 1, array_fill(0, $n + 1, 0));
for ($i = 0; $i <= $m; $i++) $dp[$i][0] = 1; // one way to build the empty word
for ($i = 1; $i <= $m; $i++) {
for ($j = 1; $j <= $n; $j++) {
$dp[$i][$j] = $dp[$i - 1][$j]; // skip s[i-1]
if ($s[$i - 1] === $t[$j - 1]) {
$dp[$i][$j] += $dp[$i - 1][$j - 1]; // or use it
}
}
}
return $dp[$m][$n];
}
echo numDistinct('BANANA', 'ANA'), "\n"; // 4
echo numDistinct('rabbbit', 'rabbit'), "\n"; // 3JavaScript
// Count the ways string t appears as a subsequence of string s.
function numDistinct(s, t) {
const m = s.length, n = t.length;
const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
for (let i = 0; i <= m; i++) dp[i][0] = 1; // one way to build the empty word
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
dp[i][j] = dp[i - 1][j]; // skip s[i-1]
if (s[i - 1] === t[j - 1]) {
dp[i][j] += dp[i - 1][j - 1]; // or use it
}
}
}
return dp[m][n];
}
console.log(numDistinct('BANANA', 'ANA')); // 4
console.log(numDistinct('rabbbit', 'rabbit')); // 3Java
public class Main {
// Count the ways string t appears as a subsequence of string s.
static int numDistinct(String s, String t) {
int m = s.length(), n = t.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 0; i <= m; i++) dp[i][0] = 1; // one way to build the empty word
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; 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
}
}
}
return dp[m][n];
}
public static void main(String[] args) {
System.out.println(numDistinct("BANANA", "ANA")); // 4
System.out.println(numDistinct("rabbbit", "rabbit")); // 3
}
}Go
package main
import "fmt"
// Count the ways string t appears as a subsequence of string s.
func numDistinct(s, t string) int {
m, n := len(s), len(t)
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, n+1)
}
for i := 0; i <= m; i++ {
dp[i][0] = 1 // one way to build the empty word
}
for i := 1; i <= m; i++ {
for j := 1; j <= n; j++ {
dp[i][j] = dp[i-1][j] // skip s[i-1]
if s[i-1] == t[j-1] {
dp[i][j] += dp[i-1][j-1] // or use it
}
}
}
return dp[m][n]
}
func main() {
fmt.Println(numDistinct("BANANA", "ANA")) // 4
fmt.Println(numDistinct("rabbbit", "rabbit")) // 3
}Time: O(m × n) · Extra space: O(m × n), or O(n) with a single row. Each cell adds at most two neighbours. Counting by brute force would try every subset of the long word.
Watch out for
- Using max instead of adding. This problem counts ways, so skip and use are summed.
- Setting the first column to 0. The empty target has exactly one way to be built.
- Only adding the diagonal on a match and forgetting the "skip" case, which always applies.
Quick check
- What is dp[i][0] for every row?
- 0
- 1
- i
- When the letters match, dp[i][j] equals...
- dp[i-1][j] + dp[i-1][j-1]
- The larger of the two
- dp[i-1][j-1] only
- How many ways does ANA hide in BANANA?
- 2
- 3
- 4