VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-common-prefix-of-all-strings/

⇱ Maximum common prefix of all strings - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum common prefix of all strings

Last Updated : 23 Jul, 2025

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:

  • All strings are inserted in TRIE by iterating on each string from A[].
  • Iterating on all strings from 1 to N.
  • For each string remove that string by calling remove().
  • Print a maximum length of string with whom the given string has the maximum common prefix by calling query().
  • Insert the same string back again in TRIE by insert().

Below is the implementation for the above approach:


Output
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:

Comment
Article Tags: