#315Longest Common SubsequenceMediumNLPAsked atGoogle · Meta · Microsoft
Longest Common Subsequence
Background
Longest Common Subsequence (LCS) is the heart of ROUGE-L and many sequence-alignment problems. Given two strings, find the longest sequence (not necessarily contiguous) of characters appearing in both, in order. Classic dynamic-programming exercise; time and space for the canonical version.
Problem statement
Implement lcs_length(a, b) returning the length of the LCS via:
Return dp[len(a)][len(b)].
Input
a—str.b—str.
Output
Returns int >= 0, the LCS length.
Examples
Example 1 — classic worked example
Input: a="ABCBDAB", b="BDCAB"
Output: 4
Explanation: LCS is BDAB (or BCAB).
Example 2 — identical strings
Input: a="abcd", b="abcd"
Output: 4
Example 3 — disjoint alphabets
Input: a="abc", b="xyz"
Output: 0
Example 4 — subsequence, not substring
Input: a="axbycz", b="abc"
Output: 3
Constraints
- Empty inputs → 0.
- time and space is acceptable; space can be reduced to as an optimisation.
Notes
- ROUGE-L. F-measure built on LCS — captures the longest aligned spans between prediction and reference without needing -gram counting.
- Edit distance vs LCS. Levenshtein = when the only allowed edits are insert/delete (no substitution). Both are sister DPs.
Python
Loading...
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •Reference classic example
- •Sample interleaved characters
- •Scattered match example