When git diff lines up two versions of a file, or a biology tool aligns two strands of DNA, it's solving the same underlying question: what's the longest run of items that appears in both sequences, in the same order, even if other items are sprinkled between them? That longest run is the longest common subsequence (LCS). A subsequence keeps the relative order of characters but does not require them to be next to each other — "ace" is a subsequence of "abcde", but "aec" is not. Your job is to return the length of the longest subsequence common to two strings.
// Returns the LENGTH of the longest common subsequence of a and b.
function longestCommonSubsequence(a: string, b: string): number;
longestCommonSubsequence('abcde', 'ace'); // → 3 ("ace" appears in both, in order)
longestCommonSubsequence('abcabba', 'cbabac'); // → 4 ("baba" appears in both, in order)
longestCommonSubsequence('GAC', 'AGCAT'); // → 2 ("GA", "AC", and "GC" are all length 2)
longestCommonSubsequence('abc', 'def'); // → 0 (no character in common)
longestCommonSubsequence('abc', 'cba'); // → 1 (order matters: only one char lines up)
longestCommonSubsequence('', 'anything'); // → 0 (empty string shares nothing)
"ae" is a valid common subsequence of "abcde" even though a and e are far apart. (A substring would require them adjacent — that is a different, stricter problem.)'abc' and 'cba' share a subsequence of length 1, not 3.return dp[m][n] is the goal. Reconstructing the actual subsequence is a follow-up, covered in the solution's "Going further".'A' and 'a' are different characters and do not match. Don't lowercase the inputs.null, numbers, or other types.