Open In App

Longest Common Subsequence (LCS) by repeatedly swapping characters of a string with characters of another string

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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.

Examples:

Input: A = “abdeff”, B = “abbet”
Output: 4
Explanation: Swapping A[5] and B[4] modifies A to “abdeft” and B to “abbef”. LCS of the given strings is “abef”. Therefore, length is 4.

Input: A = “abcd”, B = “ab”
Output: 2
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:

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the length of LCS
// possible by swapping any character
// of a string with that of another string
void lcsBySwapping(string A, string B)
{
    // Store the size of the strings
    int N = A.size();
    int M = B.size();
 
    // Stores frequency of characters
    int freq[26];
 
    memset(freq, 0, sizeof(freq));
 
    // Iterate over characters of the string A
    for (int i = 0; i < A.size(); i++) {
 
        // Update frequency of character A[i]
        freq[A[i] - 'a'] += 1;
    }
 
    // Iterate over characters of the string B
    for (int i = 0; i < B.size(); i++) {
 
        // Update frequency of character B[i]
        freq[B[i] - 'a'] += 1;
    }
 
    // Store the count of all pairs
    // of similar characters
    int cnt = 0;
 
    // Traverse the array freq[]
    for (int i = 0; i < 26; i++) {
 
        // Update cnt
        cnt += freq[i] / 2;
    }
 
    // Print the minimum of cnt, N and M
    cout << min(cnt, min(N, M));
}
 
// Driver Code
int main()
{
    // Given strings
    string A = "abdeff";
    string B = "abbet";
 
    lcsBySwapping(A, B);
 
    return 0;
}


Java




// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
// Function to find the length of LCS
// possible by swapping any character
// of a string with that of another string
static void lcsBySwapping(String A, String B)
{
     
    // Store the size of the strings
    int N = A.length();
    int M = B.length();
 
    // Stores frequency of characters
    int freq[] = new int[26];
 
    // Iterate over characters of the string A
    for(int i = 0; i < N; i++)
    {
         
        // Update frequency of character A[i]
        freq[A.charAt(i) - 'a'] += 1;
    }
 
    // Iterate over characters of the string B
    for(int i = 0; i < M; i++)
    {
         
        // Update frequency of character B[i]
        freq[B.charAt(i) - 'a'] += 1;
    }
 
    // Store the count of all pairs
    // of similar characters
    int cnt = 0;
 
    // Traverse the array freq[]
    for(int i = 0; i < 26; i++)
    {
         
        // Update cnt
        cnt += freq[i] / 2;
    }
 
    // Print the minimum of cnt, N and M
    System.out.println(Math.min(cnt, Math.min(N, M)));
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given strings
    String A = "abdeff";
    String B = "abbet";
 
    lcsBySwapping(A, B);
}
}
 
// This code is contributed by Kingash


Python3




# Python3 program for the above approach
 
# Function to find the length of LCS
# possible by swapping any character
# of a with that of another string
def lcsBySwapping(A, B):
     
    # Store the size of the strings
    N = len(A)
    M = len(B)
 
    # Stores frequency of characters
    freq = [0] * 26
 
    # Iterate over characters of the A
    for i in range(len(A)):
         
        # Update frequency of character A[i]
        freq[ord(A[i]) - ord('a')] += 1
 
    # Iterate over characters of the B
    for i in range(len(B)):
         
        # Update frequency of character B[i]
        freq[ord(B[i]) - ord('a')] += 1
 
    # Store the count of all pairs
    # of similar characters
    cnt = 0
 
    # Traverse the array freq[]
    for i in range(26):
         
        # Update cnt
        cnt += freq[i] // 2
 
    # Print the minimum of cnt, N and M
    print (min(cnt, min(N, M)))
 
# Driver Code
if __name__ == '__main__':
     
    # Given strings
    A = "abdeff"
    B = "abbet"
 
    lcsBySwapping(A, B)
 
# This code is contributed by mohit kumar 29


C#




// C# program for the above approach
using System;
 
class GFG{
 
// Function to find the length of LCS
// possible by swapping any character
// of a string with that of another string
static void lcsBySwapping(string A, string B)
{
 
    // Store the size of the strings
    int N = A.Length;
    int M = B.Length;
 
    // Stores frequency of characters
    int[] freq = new int[26];
 
    // Iterate over characters of the string A
    for(int i = 0; i < N; i++)
    {
         
        // Update frequency of character A[i]
        freq[A[i] - 'a'] += 1;
    }
 
    // Iterate over characters of the string B
    for(int i = 0; i < M; i++)
    {
         
        // Update frequency of character B[i]
        freq[B[i] - 'a'] += 1;
    }
 
    // Store the count of all pairs
    // of similar characters
    int cnt = 0;
 
    // Traverse the array freq[]
    for(int i = 0; i < 26; i++)
    {
         
        // Update cnt
        cnt += freq[i] / 2;
    }
 
    // Print the minimum of cnt, N and M
    Console.WriteLine(Math.Min(cnt, Math.Min(N, M)));
}
 
// Driver Code
public static void Main(string[] args)
{
 
    // Given strings
    string A = "abdeff";
    string B = "abbet";
 
    lcsBySwapping(A, B);
}
}
 
// This code is contributed by ukasp


Javascript




<script>
//Javascript program for the above approach
 
// Function to find the length of LCS
// possible by swapping any character
// of a string with that of another string
function lcsBySwapping(A, B)
{
    // Store the size of the strings
    var N = A.length;
    var M = B.length;
 
    // Stores frequency of characters
    var freq = new Array(26);
 
    freq.fill(0);
 
    // Iterate over characters of the string A
    for (var i = 0; i < A.length; i++) {
 
        // Update frequency of character A[i]
        freq[A[i].charCodeAt(0) - 'a'.charCodeAt(0)] += 1;
    }
 
    // Iterate over characters of the string B
    for (var i = 0; i < B.length; i++) {
 
        // Update frequency of character B[i]
        freq[B[i].charCodeAt(0) - 'a'.charCodeAt(0)] += 1;
    }
 
    // Store the count of all pairs
    // of similar characters
    var cnt = 0;
 
    // Traverse the array freq[]
    for (var i = 0; i < 26; i++) {
 
        // Update cnt
        cnt += parseInt(freq[i] / 2);
    }
 
    // Print the minimum of cnt, N and M
   document.write( Math.min(cnt, Math.min(N, M)));
}
 
var A = "abdeff";
var B = "abbet";
lcsBySwapping(A, B);
 
//This code is contributed by SoumikMondal
</script>


Output: 

4

 

Time Complexity: O(N + M)
Auxiliary Space: O(1)

 



Last Updated : 27 May, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads