Longest Common Subsequence Length
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
Two explorers wrote down, in order, the first letter of every village they visited: explorer A's log is the string a and
explorer B's log is the string b.
Return the length of the longest string that is a subsequence of both a and b (return 0 if they share no letter).
A subsequence keeps the original order but need not be contiguous: "ace" is a subsequence of "abcde", "aec" is not.
Examples
| a | b | result |
|---|---|---|
"abcde" | "ace" | 3 |
"abc" | "def" | 0 |
"aggtab" | "gxtxayb" | 4 |
Example 1 — "ace" is common to both strings.
Example 2 — No letter appears in both strings.
Example 3 — "gtab" is a longest common subsequence.
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(a: string, b: string) → int
Constraints
-
a.length -
b.length aandbconsist of lowercase English letters only.
Expected complexity
- Time
- O(NM)
- Space
- O(M)
Examples
| a | b | Expected |
|---|---|---|
"abcde" | "ace" | 3 |
"abc" | "def" | 0 |
"aggtab" | "gxtxayb" | 4 |
Hint
Hint
Let dp[i][j] be the answer for the first i letters of a and the first j letters of b: if a[i-1] == b[j-1] then
dp[i][j] = dp[i-1][j-1] + 1, otherwise max(dp[i-1][j], dp[i][j-1]). Plain branching recursion recomputes the same
(i, j) pairs exponentially often; filling the table is , and keeping only the previous row needs memory.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1000 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 14 | verdict only |
| performance | 60 | 4 | verdict only |