Longest common subsequence (recursion)
Medium TimeO(2^(m+n)) naive; O(m·n) memoised SpaceO(m + n) stack
A subsequence keeps a string's order but may skip characters, so "ace" is a subsequence of "abcde". Given two strings, return the length of the longest subsequence they share. Characters may be skipped but never reordered, they need not be adjacent in either string, and two strings sharing nothing answer 0.
Examples
Example 1
- Input
- a = 'abcde'b = 'ace'i = 0j = 0
- Output
3a,candeappear in that order in both, withbanddskipped.
Example 2
- Input
- a = 'abc'b = 'xyz'i = 0j = 0
- Output
- Not one character is common to both, so the longest shared subsequence is empty.
0
The Code
function lcs(a, b, i, j) {
if (i === a.length || j === b.length) return 0;
if (a[i] === b[j]) return 1 + lcs(a, b, i + 1, j + 1);
return Math.max(lcs(a, b, i + 1, j), lcs(a, b, i, j + 1));
}
lcs('abcde', 'ace', 0, 0);Done
More like this
All dynamic programming examples (20) →- Climbing stairs Count the ways to the top — Fibonacci in disguise.
- Coin change Try every coin and keep the cheapest way to make the amount.
- Max subarray One pass, two running totals — Kadane’s algorithm.
- Edit distance Insert, delete, or replace — take the cheapest at each mismatch.
- 0/1 Knapsack For each item, take it or leave it — keep the more valuable branch.
- House robber Rob a house and skip its neighbour, or skip to the next.