InternDoor

Longest subsequence two strings share

Mediumstrings · dynamic programming

Reported in interviews at (where)

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.

Example 1
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.

Example 2
Input
a = "abc"
b = "xyz"
Output
0

No letter is shared, so only the empty string is common.

Example 3
Input
a = "aaaa"
b = "aa"
Output
2

The shorter string is itself a subsequence of the longer one.

Limits

  • 1 <= a.length, b.length <= 1000
  • a 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

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.

Ready for the real one?

Engineering internships and entry-level jobs in India, newest first.