Longest subsequence of one string that is a substring of another
I was asked this
No reports yet. Sign in to say where you were asked it.
Given two strings x and y, return the length of the longest string t such that:
-
tis a subsequence ofx: its characters appear inxin the same order, but not necessarily next to each other. -
tis a substring ofy: it appears inyas one contiguous block.
If no non-empty t exists, return 0.
def longest_subseq_substring(x: str, y: str) -> int: ...
Constraints
0 <= len(x), len(y) <= 1000- Strings contain lowercase English letters.
Example 1
x = "sunday", y = "saturday" -> 3
"day" is contiguous in y and appears in order in x (d, a, y). No longer substring of y works: "rday" needs an r, and x has none.
Example 2
x = "axbxcx", y = "zabcz" -> 3
"abc" skips the x characters in x but is contiguous in y. Plain longest common subsequence is not the same problem: for x = "ab", y = "axb" it gives 2, but the answer here is 1, because "ab" is not contiguous in y.
Be ready to return the matching string itself, and to discuss how the solution changes if x is fixed and many different y strings arrive.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.
