Length of longest prefix anagram which are common in given two strings
Last Updated :
28 Dec, 2022
Given two strings str1 and str2 of the lengths of N and M respectively, the task is to find the length of the longest anagram string that is prefix substring of both strings.
Examples:
Input: str1 = "abaabcdezzwer", str2 = "caaabbttyh"
Output: 6
Explanation:
Prefixes of length 1 of string str1 and str2 are "a", and "c".
Prefixes of length 2 of string str1 and str2 are "ab", and "ca".
Prefixes of length 3 of string str1 and str2 are "aba", and "caa".
Prefixes of length 4 of string str1 and str2 are "abaa", and "caaa".
Prefixes of length 5 of string str1 and str2 are "abaab", and "caaab".
Prefixes of length 6 of string str1 and str2 are "abaabc", and "caaabb".
Prefixes of length 7 of string str1 and str2 are "abaabcd", and "caaabbt".
Prefixes of length 8 of string str1 and str2 are "abaabcde", and "caaabbtt".
Prefixes of length 9 of string str1 and str2 are "abaabcdez", and "caaabbtty".
Prefixes of length 10 of string str1 and str2 are "abaabcdezz", and "caaabbttyh".
Prefixes of length 6 are anagram with each other only.
Input: str1 = "abcdef", str2 = "tuvwxyz"
Output: 0
Approach: The idea is to use Hashing for solving the above problem. Follow the steps below to solve the problem:
- Initialize two integer arrays freq1[] and freq2[], each of size 26, to store the count of characters in strings str1 and str2 respectively.
- Initialize a variable, say ans, to store the result.
- Iterate over the characters of the string present in indices [0, minimum(N - 1, M - 1)] and perform the following:
- Increment count of str1[i] in freq1[] array and count of str2[i] in freq2[] array by 1.
- Check if the frequency array freq1[] is the same as the frequency array freq2[], assign ans = i + 1.
- After the above steps, print the value of ans as the result.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
#define SIZE 26
// Function to check if two arrays
// are identical or not
bool longHelper(int freq1[], int freq2[])
{
// Iterate over the range [0, SIZE]
for (int i = 0; i < SIZE; ++i) {
// If frequency any character is
// not same in both the strings
if (freq1[i] != freq2[i]) {
return false;
}
}
// Otherwise
return true;
}
// Function to find the maximum
// length of the required string
int longCommomPrefixAnagram(
string s1, string s2, int n1, int n2)
{
// Store the count of
// characters in string str1
int freq1[26] = { 0 };
// Store the count of
// characters in string str2
int freq2[26] = { 0 };
// Stores the maximum length
int ans = 0;
// Minimum length of str1 and str2
int mini_len = min(n1, n2);
for (int i = 0; i < mini_len; ++i) {
// Increment the count of
// characters of str1[i] in
// freq1[] by one
freq1[s1[i] - 'a']++;
// Increment the count of
// characters of str2[i] in
// freq2[] by one
freq2[s2[i] - 'a']++;
// Checks if prefixes are
// anagram or not
if (longHelper(freq1, freq2)) {
ans = i + 1;
}
}
// Finally print the ans
cout << ans;
}
// Driver Code
int main()
{
string str1 = "abaabcdezzwer";
string str2 = "caaabbttyh";
int N = str1.length();
int M = str2.length();
// Function Call
longCommomPrefixAnagram(str1, str2,
N, M);
return 0;
}
Java
// Java program for the above approach
public class Main
{
static int SIZE = 26;
// Function to check if two arrays
// are identical or not
static boolean longHelper(int[] freq1, int[] freq2)
{
// Iterate over the range [0, SIZE]
for (int i = 0; i < SIZE; ++i)
{
// If frequency any character is
// not same in both the strings
if (freq1[i] != freq2[i])
{
return false;
}
}
// Otherwise
return true;
}
// Function to find the maximum
// length of the required string
static void longCommomPrefixAnagram(
String s1, String s2, int n1, int n2)
{
// Store the count of
// characters in string str1
int[] freq1 = new int[26];
// Store the count of
// characters in string str2
int[] freq2 = new int[26];
// Stores the maximum length
int ans = 0;
// Minimum length of str1 and str2
int mini_len = Math.min(n1, n2);
for (int i = 0; i < mini_len; ++i) {
// Increment the count of
// characters of str1[i] in
// freq1[] by one
freq1[s1.charAt(i) - 'a']++;
// Increment the count of
// characters of str2[i] in
// freq2[] by one
freq2[s2.charAt(i) - 'a']++;
// Checks if prefixes are
// anagram or not
if (longHelper(freq1, freq2)) {
ans = i + 1;
}
}
// Finally print the ans
System.out.print(ans);
}
// Driver code
public static void main(String[] args)
{
String str1 = "abaabcdezzwer";
String str2 = "caaabbttyh";
int N = str1.length();
int M = str2.length();
// Function Call
longCommomPrefixAnagram(str1, str2, N, M);
}
}
// This code is contributed by divyeshrrabadiya07.
Python3
# Python3 program for the above approach
SIZE = 26
# Function to check if two arrays
# are identical or not
def longHelper(freq1, freq2):
# Iterate over the range [0, SIZE]
for i in range(26):
# If frequency any character is
# not same in both the strings
if (freq1[i] != freq2[i]):
return False
# Otherwise
return True
# Function to find the maximum
# length of the required string
def longCommomPrefixAnagram(s1, s2, n1, n2):
# Store the count of
# characters in str1
freq1 = [0]*26
# Store the count of
# characters in str2
freq2 = [0]*26
# Stores the maximum length
ans = 0
# Minimum length of str1 and str2
mini_len = min(n1, n2)
for i in range(mini_len):
# Increment the count of
# characters of str1[i] in
# freq1[] by one
freq1[ord(s1[i]) - ord('a')] += 1
# Increment the count of
# characters of stord(r2[i]) in
# freq2[] by one
freq2[ord(s2[i]) - ord('a')] += 1
# Checks if prefixes are
# anagram or not
if (longHelper(freq1, freq2)):
ans = i + 1
# Finally print the ans
print (ans)
# Driver Code
if __name__ == '__main__':
str1 = "abaabcdezzwer"
str2 = "caaabbttyh"
N = len(str1)
M = len(str2)
# Function Call
longCommomPrefixAnagram(str1, str2, N, M)
# This code is contributed by mohit kumar 29.
C#
// C# program for the above approach
using System;
class GFG
{
static int SIZE = 26;
// Function to check if two arrays
// are identical or not
static bool longHelper(int[] freq1, int[] freq2)
{
// Iterate over the range [0, SIZE]
for (int i = 0; i < SIZE; ++i)
{
// If frequency any character is
// not same in both the strings
if (freq1[i] != freq2[i])
{
return false;
}
}
// Otherwise
return true;
}
// Function to find the maximum
// length of the required string
static void longCommomPrefixAnagram(
string s1, string s2, int n1, int n2)
{
// Store the count of
// characters in string str1
int[] freq1 = new int[26];
// Store the count of
// characters in string str2
int[] freq2 = new int[26];
// Stores the maximum length
int ans = 0;
// Minimum length of str1 and str2
int mini_len = Math.Min(n1, n2);
for (int i = 0; i < mini_len; ++i) {
// Increment the count of
// characters of str1[i] in
// freq1[] by one
freq1[s1[i] - 'a']++;
// Increment the count of
// characters of str2[i] in
// freq2[] by one
freq2[s2[i] - 'a']++;
// Checks if prefixes are
// anagram or not
if (longHelper(freq1, freq2)) {
ans = i + 1;
}
}
// Finally print the ans
Console.Write(ans);
}
// Driver code
static void Main() {
string str1 = "abaabcdezzwer";
string str2 = "caaabbttyh";
int N = str1.Length;
int M = str2.Length;
// Function Call
longCommomPrefixAnagram(str1, str2, N, M);
}
}
// This code is contributed by divyesh072019.
JavaScript
<script>
// Javascript program for the above approach
let SIZE = 26;
// Function to check if two arrays
// are identical or not
function longHelper(freq1, freq2)
{
// Iterate over the range [0, SIZE]
for(let i = 0; i < SIZE; ++i)
{
// If frequency any character is
// not same in both the strings
if (freq1[i] != freq2[i])
{
return false;
}
}
// Otherwise
return true;
}
// Function to find the maximum
// length of the required string
function longCommomPrefixAnagram(s1, s2, n1, n2)
{
// Store the count of
// characters in string str1
let freq1 = new Array(26);
freq1.fill(0);
// Store the count of
// characters in string str2
let freq2 = new Array(26);
freq2.fill(0);
// Stores the maximum length
let ans = 0;
// Minimum length of str1 and str2
let mini_len = Math.min(n1, n2);
for(let i = 0; i < mini_len; ++i)
{
// Increment the count of
// characters of str1[i] in
// freq1[] by one
freq1[s1[i].charCodeAt() -
'a'.charCodeAt()]++;
// Increment the count of
// characters of str2[i] in
// freq2[] by one
freq2[s2[i].charCodeAt() -
'a'.charCodeAt()]++;
// Checks if prefixes are
// anagram or not
if (longHelper(freq1, freq2))
{
ans = i + 1;
}
}
// Finally print the ans
document.write(ans);
}
// Driver code
let str1 = "abaabcdezzwer";
let str2 = "caaabbttyh";
let N = str1.length;
let M = str2.length;
// Function Call
longCommomPrefixAnagram(str1, str2, N, M);
// This code is contributed by rameshtravel07
</script>
Time Complexity: O(N*26)
Auxiliary Space: O(1)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read