← Questions

Longest subsequence of one string that is a substring of another

0
MicrosoftCoding

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:

  • t is a subsequence of x: its characters appear in x in the same order, but not necessarily next to each other.
  • t is a substring of y: it appears in y as 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 0 correct 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 longest t that ends exactly at y[j - 1], is contiguous in y, and is a subsequence of x[:i].
  • Transition: if x[i - 1] == y[j - 1], extend dp[i - 1][j - 1]. Otherwise keep dp[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 y and greedily matches forward in x, which is also O(|x| x |y|).
  • Reduces memory to O(|y|) with one rolling row.
  • Tests empty strings, no shared letters, y contained in x as a subsequence, and both examples.

Follow-ups

  • Return the string itself.
  • x is fixed and many y strings arrive: precompute, for each position of x, the next index of each letter.
  • Count the substrings of y that are subsequences of x.
  • Allow uppercase letters and any Unicode text.

Where it's asked

What it tests

dynamic programming · strings · subsequence

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding