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.
A coding interview question asked at Microsoft. It tests dynamic programming, strings and subsequence.
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.
Clarifying questions
- Is the answer only the length, or also the string
t? - When several strings tie, which one should be returned?
- Is
0correct when either string is empty? - Is O(len(x) x len(y)) time fine for strings up to 1000?
What a strong answer covers
- Defines the DP state clearly:
dp[i][j]is the longesttthat ends exactly aty[j - 1], is contiguous iny, and is a subsequence ofx[:i]. - Transition: if
x[i - 1] == y[j - 1], extenddp[i - 1][j - 1]. Otherwise keepdp[i - 1][j]. The answer is the largest value. - Explains why this differs from both LCS and the longest common substring, using the
"ab"/"axb"example. - Or tries each start in
yand greedily matches forward inx, which is also O(|x| x |y|). - Reduces memory to O(|y|) with one rolling row.
- Tests empty strings, no shared letters,
ycontained inxas a subsequence, and both examples.
Follow-ups
- Return the string itself.
-
xis fixed and manyystrings arrive: precompute, for each position ofx, the next index of each letter. - Count the substrings of
ythat are subsequences ofx. - Allow uppercase letters and any Unicode text.
Where it's asked
What it tests
dynamic programming · strings · subsequence
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
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 submit your code; every attempt is kept here.
