
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find the longest common prefix between two strings after performing swaps on second string in C++
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.
Example
#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 break; } cout<<"Length of longest common prefix: " << c; } int main() { string str1="here", str2 = "there"; longestPrefix(str1, str2); }
Output
Length of longest common prefix: 4
- Related Articles
- Program to find longest common prefix from list of strings in Python
- Finding the longest common consecutive substring between two strings in JavaScript
- Longest Common Prefix in Python
- Find minimum shift for longest common prefix in C++
- How to find the longest common substring from more than two strings in Python?
- Longest possible string built from two strings in JavaScript
- C++ program to find maximum distance between two rival students after x swaps
- Find the longest sub-string which is prefix, suffix and also present inside the string in Python
- Python – Split Strings on Prefix Occurrence
- Final string after performing given operations in C++
- Program to find length of longest common subsequence of three strings in Python
- Longest Happy Prefix in C++
- How to find the number of common words between two string vectors in R?
- Longest Well-Performing Interval in Python
- Program to perform prefix compression from two strings in Python

Advertisements