![]() |
VOOZH | about |
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:
Below is the implementation of the above approach:
6
Time Complexity: O(N*26)
Auxiliary Space: O(1)