Find the longest common prefix between two strings after performing swaps on second string in C++

C++Server Side ProgrammingProgramming

Suppose we have two strings str1 and str2. Find the longest common prefix between them after performing zero or more operation on the second string. In each operation, we can swap any two letters. So if str1 = “HERE”, str2 = “THERE”, then output will be 4. The second string can be made “HERET” by just swapping the characters. So the longest prefix is of length 4.

As we know that we can only swap on str2. And the length of the matrix should be maximized. So the idea is to traverse str1, and check if the frequency of the current character in str1 is same or less of that in str2. If yes, then move forward in string a, otherwise break and print the length of the part of string str1, up to which a character is matched in string str2.


 Live Demo

#include <iostream>
using namespace std;
void longestPrefix(string str1, string str2) {
   int frequency[26]={0};
   int a = str1.length();
   int b = str2.length();
   for (int i=0 ;i<b ; i++) {
      frequency[str2[i] - 97] += 1;
   int c = 0;
   for (int i=0 ;i<a ; i++) {
      if (frequency[str1[i] - 97] > 0){
         c += 1;
         frequency[str1[i] - 97] -= 1;
      } else
   cout<<"Length of longest common prefix: " << c;
int main() {
   string str1="here", str2 = "there";
   longestPrefix(str1, str2);


Length of longest common prefix: 4
Updated on 18-Dec-2019 12:35:42