![]() |
VOOZH | about |
Given array A[] of strings of size N, the task for this problem is to print the Maximum Common prefix of string 'i' with other strings from 1 to N apart from 'i' itself for all given strings from 1 to N. Given strings consists of lowercase English letters.
Examples:
Input: {"abc", "abb", "aac"}
Output: 2 2 1
Explanation:
- Answer for first string is two. since first string has maximum length of common prefix is 2. with one of the all other strings.
- Answer for second string is two. since second string has maximum length of common prefix is 2 with one of the all other strings.
- Answer for third string is one. since third string has maximum length of common prefix is 1 with one of the all other strings.
Input: A2 = {"abracadabra", "bracadabra", "racadabra", "acadabra", "cadabra", "adabra", "dabra", "abra", "bra", "ra", "a"}
Output: 4 3 2 1 0 1 0 4 3 2 1
Naive approach: The basic way to solve the problem is as follows:
The basic way to solve this problem is to iterate all other strings for each strings and maintain maximum count.
Time Complexity: O(N2)
Auxiliary Space: O(N)
Efficient Approach: The above approach can be optimized based on the following idea:
Trie data structure can be used to solve this problem.
Follow the steps below to solve the problem:
Below is the implementation for the above approach:
2 2 1 4 3 2 1 0 1 0 4 3 2 1
Time Complexity: O(N*K2), where N is the number of strings and K is the maximum length of the strings.
Auxiliary Space: O(N*K)
Related Articles: