Find longest subsequence of x that is a substring of y
Problem Description
Given two strings, x and y, compute the maximum length of a string s that satisfies both of the following conditions:
sis a subsequence ofx(meaningscan be formed by deleting zero or more characters fromxwithout changing the order of the remaining characters).sis a substring ofy(meaningsmust appear as a contiguous block of characters withiny).
Return the maximum possible length of such a string s.
Examples
-
Example 1:
x = "abcd"y = "abdc"- Output:
3(One optimal choice is"abd", which is a subsequence ofxand a substring ofy.)
-
Example 2:
x = "hackerranks"y = "hackers"- Output:
7(The string"hackers"is both a subsequence ofxand a substring ofy.)
AI interview prep
Core dilemma
The central engineering conflict is efficiently identifying and validating potential candidates (substrings of `y`) against the subsequence constraint of `x` to find the longest match, avoiding combinatorial explosion. The challenge lies in optimizing the repeated subsequence checks.
3 tradeoffs and 3 stress tests locked
Interview prep
Unlock the interviewer X-Ray rubric, tradeoff matrix, stress tests, clarifying questions, and key concepts.
Find longest subsequence of x that is a substring of y
Problem Description
Given two strings, x and y, compute the maximum length of a string s that satisfies both of the following conditions:
sis a subsequence ofx(meaningscan be formed by deleting zero or more characters fromxwithout changing the order of the remaining characters).sis a substring ofy(meaningsmust appear as a contiguous block of characters withiny).
Return the maximum possible length of such a string s.
Examples
-
Example 1:
x = "abcd"y = "abdc"- Output:
3(One optimal choice is"abd", which is a subsequence ofxand a substring ofy.)
-
Example 2:
x = "hackerranks"y = "hackers"- Output:
7(The string"hackers"is both a subsequence ofxand a substring ofy.)