Longest subsequence two strings share
A subsequence of a string is what is left after deleting any number of its characters (none at all is allowed) without changing the order of the rest. "rvw" is a subsequence of "review"; "wvr" is not.
Return the length of the longest string that is a subsequence of both a and b.
- Input
a = "interview"
b = "review"- Output
5
"rview" is in both. "review" is not a subsequence of "interview": after its r there is no e before the v.
- Input
a = "abc"
b = "xyz"- Output
0
No letter is shared, so only the empty string is common.
- Input
a = "aaaa"
b = "aa"- Output
2
The shorter string is itself a subsequence of the longer one.
Limits
1 <= a.length, b.length <= 1000a and b hold lowercase English letters
Hints
Hint 1
Let best(i, j) be the answer for the first i letters of a and the first j letters of b. If a[i - 1] equals b[j - 1], that letter can end the subsequence: best(i - 1, j - 1) + 1.
Hint 2
Otherwise one of the two last letters is not used: max(best(i - 1, j), best(i, j - 1)). Fill the table row by row; only the previous row is needed.
Where this was reported
- UST, Software engineer on-campus interview, Pune, 2023 (GeeksforGeeks)
- Aptiv, Software engineer off-campus interview, 2022 (Code360)
- Infosys, Specialist Programmer interview, 2026 (GeeksforGeeks)
Our own problem on the task these candidates describe; the wording, examples and tests are InternDoor’s.
Run your code to check it on the examples. Submit runs every hidden test.


