Longest Common Subsequence (LCS) by repeatedly swapping characters of a string with characters of another string
Given two strings A and B of lengths N and M respectively, the task is to find the length of the longest common subsequence that can be two strings if any character from string A can be swapped with any other character from B any number of times.
Input: A = “abdeff”, B = “abbet”
Explanation: Swapping A and B modifies A to “abdeft” and B to “abbef”. LCS of the given strings is “abef”. Therefore, length is 4.
Input: A = “abcd”, B = “ab”
Explanation: LCS of the given strings is “ab”. Therefore, length is 2.
Approach: The idea is based on the observation that if any character from string A can be swapped with any other character from string B, then it is also possible to swap characters within string A and also within string B.
Proof: If characters A[i] and A[j] are required to be swapped, then take a temporary element at any index k in string B. Follow the steps below to solve the problem:
- Swap A[i] with B[k].
- Swap B[k] with A[j].
- Swap B[k] with A[i].
In this way, the characters within a string can be swapped. Now, the elements can be arranged in any order. Therefore, the idea is to find the frequencies of all the characters present in both the strings and divide them equally.
Follow the steps below to solve the problem:
- Initialize an array, say freq, of size 26, to store the frequency of each character present in the strings.
- Traverse the strings A and B and update the frequency of each character in the array freq.
- Initialize a variable, say cnt, to store the required length.
- Traverse the array freq and increase the value of cnt by freq[i] / 2.
- Store the minimum of cnt, N, and M in a variable, say ans.
- Print the value of ans as the result.
Below is the implementation of the above approach:
Time Complexity: O(N + M)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.