Length of longest prefix anagram which are common in given two strings

In this article, we delve into a fascinating problem in the realm of string manipulation and anagram analysis. Specifically, we'll be finding the length of the longest prefix anagram that is common to two given strings. Our solution leverages C++, a powerful and versatile programming language beloved by software developers.

Understanding Anagrams

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. For instance, the words 'listen' and 'silent' are anagrams of each other.

Problem Statement

Given two strings, we need to find the length of the longest prefix anagram present in both strings. A prefix is a substring that starts from the first character of a string.

Solution Approach

To solve this problem, we'll follow these steps:

  • Initialization  Initialize an integer array of size 26 (representing the 26 English alphabets) for each string. These arrays will store the frequency count of each character in the prefix of the strings.

  • Frequency Counting  For each character in the string's prefix, increment the corresponding index in the array.

  • Comparison  Compare the frequency arrays of the two strings. Find the minimum frequency of each character, and sum these frequencies.

  • Return Result  The sum is the length of the longest common anagram prefix.

C++ Implementation


Here's the C++ code for our problem solution 

#include <bits/stdc++.h>
using namespace std;

int longestCommonPrefixAnagram(string str1, string str2) {
   int n1 = str1.length(), n2 = str2.length();
   vector<int> count1(26, 0), count2(26, 0);
   for (int i = 0; i < n1; i++)
      count1[str1[i] - 'a']++;
   for (int i = 0; i < n2; i++)
      count2[str2[i] - 'a']++;
   int result = 0;
   for (int i = 0; i < 26; i++)
      result += min(count1[i], count2[i]);
   return result;

int main() {
   string str1 = "abcdef";
   string str2 = "fedcba";
   int result = longestCommonPrefixAnagram(str1, str2);
   cout << "Length of longest common prefix anagram: " << result << endl;
   return 0;


Length of longest common prefix anagram: 6


Let's consider the strings −

str1 = "abcdef", str2 = "fedcba"

After counting the frequencies of each character, we find that both strings contain exactly the same characters (albeit in a different order). Hence, the longest common prefix anagram is the entire string, and its length is 6, which is the output of our program.


The problem of finding the length of the longest prefix anagram common in two strings is an interesting one that tests our understanding of string manipulation and frequency counting. This solution illustrates how we can use basic C++ programming constructs to solve it efficiently.

Updated on: 18-May-2023


Kickstart Your Career

Get certified by completing the course

Get Started