FastPrepFastPrep
Problem Brief

Longest Subsequence which is a Substring

FULLTIMEOA

For MTS role

You are given two strings x and y. You need to find the length of the longest subsequence of x that is also a substring of y.

A subsequence is a sequence derived from another string by deleting some or no elements without changing the order.

A substring is a contiguous part of a string.

Function Description

Complete the function longestSubsequenceWhichIsSubstring in the editor.

longestSubsequenceWhichIsSubstring has the following parameters:

  1. String x: the first string
  2. String y: the second string

Returns

int: the length of the longest subsequence of x that is also a substring of y

Approach

I generated all substrings of y and checked if they are subsequences of x.

Used a helper function for checking subsequence in O(M) time using two pointers.

Time complexity: O(N² * M), where N = len(y), M = len(x).

1Example 1

Input
x = "abcd", y = "abdc"
Output
3
Explanation
The subsequence "abd" is present in x and also appears as a substring in y.
public int longestSubsequenceWhichIsSubstring(String x, String y) {
  // write your code here
}
Input

x

"abcd"

y

"abdc"

Output

3

Sign in to submit your solution.