Monday, March 22, 2021

Published March 22, 2021 by Anonymous with 0 comment

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

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.

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++

#include <bits/stdc++.h>

using namespace std;

  

void lcsBySwapping(string A, string B)

{

    

    int N = A.size();

    int M = B.size();

  

    

    int freq[26];

  

    memset(freq, 0, sizeof(freq));

  

    

    for (int i = 0; i < A.size(); i++) {

  

        

        freq[A[i] - 'a'] += 1;

    }

  

    

    for (int i = 0; i < B.size(); i++) {

  

        

        freq[B[i] - 'a'] += 1;

    }

  

    

    

    int cnt = 0;

  

    

    for (int i = 0; i < 26; i++) {

  

        

        cnt += freq[i] / 2;

    }

  

    

    cout << min(cnt, min(N, M));

}

  

int main()

{

    

    string A = "abdeff";

    string B = "abbet";

  

    lcsBySwapping(A, B);

  

    return 0;

}

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.

Let's block ads! (Why?)


Original page link

Best Cool Tech Gadgets

Top favorite technology gadgets
      edit

0 comments:

Post a Comment