Longest Subsequence which is a Substring
Learn this problemProblem statement
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
longestSubsequenceWhichIsSubstring(x: String, y: String) → int
Complete the function longestSubsequenceWhichIsSubstring in the editor.
longestSubsequenceWhichIsSubstring has the following parameters:
String x: the first stringString 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).
Examples
Example 1
x = "abcd"y = "abdc"return = 3x and also appears as a substring in y.Example 2
x = "hackerranks"y = "hackers"return = 7"hackers" is a substring of y and also a subsequence of x, so the answer is 7.
Constraints
1 <= x.length, y.length <= 2000xandycontain lowercase English letters.
More Salesforce problems
- Diameter of an Acyclic Undirected GraphONSITE INTERVIEW · Seen Jul 2026
- Optimal Account BalancingPHONE SCREEN · Seen Jul 2026
- Longest Increasing SubsequencePHONE SCREEN · Seen Jul 2026
- Maximal SquarePHONE SCREEN · Seen Jul 2026
- Maximum Barbell WeightOA · Seen Jul 2026
- Minimum No-Repeat Segments After One Character RemovalOA · Seen Jul 2026
- Minimum Operations to ZeroOA · Seen Jul 2026
- Minimize Total Input Cost (for LTMS)OA · Seen Jun 2026