Length of longest prefix anagram which are common in given two strings | C ++ program for the above approach ; Function to check if two arrays are identical or not ; Iterate over the range [ 0 , SIZE ] ; If frequency any character is not same in both the strings ; Otherwise ; Function to find the maximum length of the required string ; Store the count of characters in string str1 ; Store the count of characters in string str2 ; Stores the maximum length ; Minimum length of str1 and str2 ; Increment the count of characters of str1 [ i ] in freq1 [ ] by one ; Increment the count of characters of str2 [ i ] in freq2 [ ] by one ; Checks if prefixes are anagram or not ; Finally print the ans ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define SIZE  26 NEW_LINE bool longHelper ( int freq1 [ ] , int freq2 [ ] ) { for ( int i = 0 ; i < SIZE ; ++ i ) { if ( freq1 [ i ] != freq2 [ i ] ) { return false ; } } return true ; } int longCommomPrefixAnagram ( string s1 , string s2 , int n1 , int n2 ) { int freq1 [ 26 ] = { 0 } ; int freq2 [ 26 ] = { 0 } ; int ans = 0 ; int mini_len = min ( n1 , n2 ) ; for ( int i = 0 ; i < mini_len ; ++ i ) { freq1 [ s1 [ i ] - ' a ' ] ++ ; freq2 [ s2 [ i ] - ' a ' ] ++ ; if ( longHelper ( freq1 , freq2 ) ) { ans = i + 1 ; } } cout << ans ; } int main ( ) { string str1 = " abaabcdezzwer " ; string str2 = " caaabbttyh " ; int N = str1 . length ( ) ; int M = str2 . length ( ) ; longCommomPrefixAnagram ( str1 , str2 , N , M ) ; return 0 ; }