![]() |
VOOZH | about |
Given a string s, the task is to find the longest repeating subsequence, such that the two subsequences don’t have the same string character at the same position, i.e. any ith character in the two subsequences shouldn’t have the same index in the original string.
Examples:
Input: s = "aabb"
Output: "ab"
Explanation: The longest repeated subsequence is "ab", formed by matching 'a' from positions 1 and 2, and 'b' from positions 3 and 4.Input: s = "aab"
Output: "a"
Explanation: The two subsequences are 'a'(first) and 'a' (second). Note that 'b' cannot be considered as part of a subsequence as it would be at the same index in both.
This problem is just the modification of the Longest Common Subsequence problem. The idea is to find the LCS(s, s) where s is the input string with the restriction that when both the characters are the same, they shouldn't be on the same index in the two strings. We have discussed a solution to find the length of the longest repeated subsequence.
2
Time Complexity: O(n*n), where n is the length of string s.
Auxilairy Space: O(n*n)
The above solution only finds length of subsequence. We can print the subsequence using dp[n+1][n+1] table The idea is similar to printing LCS.
ABD
Time Complexity: O(n*n), where n is the length of string s.
Auxilairy Space: O(n*n)