Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap"http://www.geeksforgeeks.org/longest-common-prefix-set-5-using-trie/
// Counts and returns the number of children of the
// current node
int
countChildren(
struct
TrieNode *node,
int
*index)
{
int
count = 0;
for
(
int
i=0; i<ALPHABET_SIZE; i++)
{
if
(node->children[i] != NULL)
{
count++;
*index = i;
}
}
return
(count);
}
// Peform a walk on the trie and return the
// longest common prefix string
string walkTrie(
struct
TrieNode *root)
{
struct
TrieNode *pCrawl = root;
int
index;
string prefix;
while
(countChildren(pCrawl, &index) == 1)
{
pCrawl = pCrawl->children[index];
prefix.push_back(
'a'
+index);
}
return
(prefix);
}
// A Function to construct trie
void
constructTrie(string arr[],
int
n,
struct
TrieNode *root)
{
for
(
int
i = 0; i < n; i++)
insert (root, arr[i]);
return
;
}
// A Function that returns the longest common prefix
// from the array of strings
string commonPrefix(string arr[],
int
n)
{
struct
TrieNode *root = getNode();
constructTrie(arr, n, root);
// Perform a walk on the trie
return
walkTrie(root);
}
- Find the string having the minimum length. Let this length be L.
- Perform a binary search on any one string (from the input array of strings). Let us take the first string and do a binary search on the characters from the index – 0 to L-1.
- Initially, take low = 0 and high = L-1 and divide the string into two halves – left (low to mid) and right (mid+1 to high).
- Check whether all the characters in the left half is present at the corresponding indices (low to mid) of all the strings or not. If it is present then we append this half to our prefix string and we look in the right half in a hope to find a longer prefix.(It is guaranteed that a common prefix string is there.)
- Otherwise, if all the characters in the left half is not present at the corresponding indices (low to mid) in all the strings, then we need not look at the right half as there is some character(s) in the left half itself which is not a part of the longest prefix string. So we indeed look at the left half in a hope to find a common prefix string. (It may be possible that we don’t find any common prefix string)
Time Complexity :
The recurrence relation is
The recurrence relation is
T(M) = T(M/2) + O(MN)
where
N = Number of strings M = Length of the largest string string
So we can say that the time complexity is O(NM log M)
Auxiliary Space: To store the longest prefix string we are allocating space which is O(N) where, N = length of the largest string among all the strings
bool
allContainsPrefix(string arr[],
int
n, string str,
int
start,
int
end)
{
for
(
int
i=0; i<=n-1; i++)
for
(
int
j=start; j<=end; j++)
if
(arr[i][j] != str[j])
return
(
false
);
return
(
true
);
}
// A Function that returns the longest common prefix
// from the array of strings
string commonPrefix(string arr[],
int
n)
{
int
index = findMinLength(arr, n);
string prefix;
// Our resultant string
// We will do an in-place binary search on the
// first string of the array in the range 0 to
// index
int
low = 0, high = index;
while
(low <= high)
{
// Same as (low + high)/2, but avoids overflow
// for large low and high
int
mid = low + (high - low) / 2;
if
(allContainsPrefix (arr, n, arr[0], low, mid))
{
// If all the strings in the input array contains
// this prefix then append this substring to
// our answer
prefix = prefix + arr[0].substr(low, mid-low+1);
// And then go for the right part
low = mid + 1;
}
else
// Go for the left part
high = mid - 1;
}
return
(prefix);
}
Time Complexity : Since we are iterating through all the characters of all the strings, so we can say that the time complexity is O(N M) where,
N = Number of strings M = Length of the largest string string
Auxiliary Space : To store the longest prefix string we are allocating space which is O(M Log N).
// A Utility Function to find the common prefix between
// strings- str1 and str2
string commonPrefixUtil(string str1, string str2)
{
string result;
int
n1 = str1.length(), n2 = str2.length();
// Compare str1 and str2
for
(
int
i=0, j=0; i<=n1-1&&j<=n2-1; i++,j++)
{
if
(str1[i] != str2[j])
break
;
result.push_back(str1[i]);
}
return
(result);
}
// A Function that returns the longest common prefix
// from the array of strings
string commonPrefix (string arr[],
int
n)
{
string prefix = arr[0];
for
(
int
i=1; i<=n-1; i++)
prefix = commonPrefixUtil(prefix, arr[i]);
return
(prefix);
}
Time Complexity : Since we are iterating through all the strings and for each string we are iterating though each characters, so we can say that the time complexity is O(N M) where,
N = Number of strings M = Length of the largest string string
Auxiliary Space : To store the longest prefix string we are allocating space which is O(M).
string commonPrefix(string arr[],
int
n)
{
int
minlen = findMinLength(arr, n);
string result;
// Our resultant string
char
current;
// The current character
for
(
int
i=0; i<minlen; i++)
{
// Current character (must be same
// in all strings to be a part of
// result)
current = arr[0][i];
for
(
int
j=1 ; j<n; j++)
if
(arr[j][i] != current)
return
result;
// Append to result
result.push_back(current);
}
return
(result);
}
How is this algorithm better than the “Word by Word Matching” algorithm ?-
In Set 1 we discussed about the “Word by Word Matching” Algorithm.
Suppose you have the input strings as- “geeksforgeeks”, “geeks”, “geek”, “geezer”, “x”.
Now there is no common prefix string of the above strings. By the “Word by Word Matching” algorithm discussed in Set 1, we come to the conclusion that there is no common prefix string by traversing all the strings. But if we use this algorithm, then in the first iteration itself we will come to know that there is no common prefix string, as we don’t go further to look for the second character of each strings.
This algorithm has a huge advantage when there are too many strings.
Time Complexity : Since we are iterating through all the characters of all the strings, so we can say that the time complexity is O(N M) where,
N = Number of strings M = Length of the largest string string
Auxiliary Space : To store the longest prefix string we are allocating space which is O(M).