 Open in App
Not now

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

• Difficulty Level : Medium
• Last Updated : 27 May, 2021

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 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”
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 ` `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;`   `    ``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``;`   `    ``// 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

 ``

Output:

`4`

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

My Personal Notes arrow_drop_up
Related Articles