![]() |
VOOZH | about |
Given two strings s1 and s2, the task is to find the length of the longest common subsequence with no repeating character.
Examples:
Input: s1= "aabbcc", s2= "aabc"
Output: 3
Explanation: "aabc" is longest common subsequence but it has two repeating character 'a'.
So the required longest common subsequence with no repeating character is "abc".Input: s1= "aabcad", s2= "adbcwcad"
Output: 4
Explanation: The subsequences are "abcd" or "bcad".
Approach: The approach to solve the problem is similar to that of the longest common subsequence using recursion but, also needs to keep track that no two characters are repeated in a subsequence. Follow the steps mentioned below:
Below is the implementation of the above approach.
3
Time Complexity: O(N * 2N) where N is max(size of s1, size of s2).
Auxiliary Space: O(1)
Efficient approach: An efficient approach is to use memoization to reduce the time complexity. Create a 2D dp[][] array where dp[i][j] stores the length of the longest common subsequence with no repeating character till ith index of s1 and jth index of s2 is considered. If characters at s1[i] and s2[j] are same then dp[i][j] = dp[i-1][j-1] + 1, otherwise dp[i][j] = max(dp[i-1][j], dp[i][j-1]). Just keep track of repeating characters as mentioned in the above approach along with this.
Note: In the implementation, the dp array is implemented using map where the key is the concatenated string of i and j.
Given below is the implementation of the above approach.
3
Time Complexity: O(N * M) where N is the size of s1 and M is the size of s2
Auxiliary Space: O(N * M)