Find longest subsequence of x that is a substring of y
Company: Salesforce
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: HR Screen
Quick Answer: This question evaluates string-algorithm skills and conceptual understanding of subsequences versus substrings, along with attention to algorithmic efficiency when relating non-contiguous selections to contiguous patterns.
Constraints
- 0 <= len(x), len(y)
- Strings consist of printable characters (typically lowercase English letters in the examples).
- The answer is 0 when no character of y appears in x, or when either string is empty.
- The result never exceeds min(len(x), len(y)).
Examples
Input: ("abcd", "abdc")
Expected Output: 3
Explanation: "abd" is a subsequence of x="abcd" and a substring of y="abdc", length 3. No length-4 substring of y is a subsequence of x.
Input: ("hackerranks", "hackers")
Expected Output: 7
Explanation: The whole of y="hackers" is a subsequence of x="hackerranks" (drop the extra r, n, s), so the answer is its full length 7.
Input: ("", "abc")
Expected Output: 0
Explanation: x is empty, so the only common string is the empty string; length 0.
Input: ("abc", "")
Expected Output: 0
Explanation: y is empty, so there is no non-empty substring of y; length 0.
Input: ("aaaa", "aa")
Expected Output: 2
Explanation: y="aa" is a subsequence of x="aaaa", so the whole substring of length 2 qualifies.
Input: ("abc", "xyz")
Expected Output: 0
Explanation: x and y share no characters, so no non-empty substring of y is a subsequence of x; length 0.
Input: ("abcabc", "abcabc")
Expected Output: 6
Explanation: y equals x, and any string is a subsequence of itself, so the whole length-6 substring qualifies.
Input: ("a", "a")
Expected Output: 1
Explanation: Single matching character; the substring "a" of y is a subsequence of x, length 1.
Hints
- Every valid s is a contiguous substring of y. Enumerate substrings y[i..j] and test each against x.
- Testing whether a string t is a subsequence of x is a single two-pointer pass: walk through x once, advancing a pointer in t whenever characters match; t is a subsequence iff the pointer reaches the end of t.
- Pruning: if y[i..j] is not a subsequence of x, then no longer substring starting at i can be either — break out of the inner loop. Also skip any candidate whose length is not greater than the best found so far.