Java Program To Find Longest Common Prefix Using Word By Word Matching
Last Updated :
18 Aug, 2023
Given a set of strings, find the longest common prefix.
Examples:
Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”}
Output : "gee"
Input : {"apple", "ape", "april"}
Output : "ap"
We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks”. What is the longest common prefix in both of them? It is “geeks”.
Now let us introduce another word, “geek”. So now what is the longest common prefix in these three words ? It is “geek”
We can see that the longest common prefix holds the associative property, i.e-
LCP(string1, string2, string3)
= LCP (LCP (string1, string2), string3)
Like here
LCP (“geeksforgeeks”, “geeks”, “geek”)
= LCP (LCP (“geeksforgeeks”, “geeks”), “geek”)
= LCP (“geeks”, “geek”) = “geek”
So we can make use of the above associative property to find the LCP of the given strings. We one by one calculate the LCP of each of the given string with the LCP so far. The final result will be our longest common prefix of all the strings.
Note that it is possible that the given strings have no common prefix. This happens when the first character of all the strings are not the same.
We show the algorithm with the input strings- “geeksforgeeks”, “geeks”, “geek”, “geezer” by the below figure.

Below is the implementation of above approach:
Java
// Java Program to find the longest
// common prefix
class GFG {
// A Utility Function to find the common
// prefix between strings- str1 and str2
static 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.charAt(i) != str2.charAt(j))
{
break;
}
result += str1.charAt(i);
}
return (result);
}
// A Function that returns the longest
// common prefix from the array of strings
static 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);
}
// Driver code
public static void main(String[] args)
{
String arr[] = {"geeksforgeeks", "geeks",
"geek", "geezer"};
int n = arr.length;
String ans = commonPrefix(arr, n);
if (ans.length() > 0)
{
System.out.printf("The longest common prefix is - %s",
ans);
}
else
{
System.out.printf("There is no common prefix");
}
}
}
// This code is contributed by 29AjayKumar
Output :
The longest common prefix is - gee
Time Complexity : Since we are iterating through all the strings and for each string we are iterating though each character, 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). Please refer to complete article on Longest Common Prefix using Word by Word Matching for more details!
Another approach to Find Longest Common Prefix Using Word By Word Matching, in this we use divide and conquer approach. The basic idea of this approach is to divide the array of string into smaller subarrays and then find the common prefix among them recursively.it uses the recursive function commonPrefix(arr, low, high) that takes an array of strings. A lower bound, and an upper bound as input. It divides the array into two smaller subarrays recursively and finds the common prefix among them by calling the commonPrefixUtil(str1, str2) function.
Java
public class LongestCommonPrefix {
// recursive method to find the longest common prefix
static String commonPrefix(String[] arr, int low, int high) {
// base case: if the array has only one element, return it
if (low == high)
return (arr[low]);
// recursive case: divide the array into two sub-arrays
if (high > low) {
int mid = low + (high - low) / 2;
// find the common prefix of the left sub-array
String str1 = commonPrefix(arr, low, mid);
// find the common prefix of the right sub-array
String str2 = commonPrefix(arr, mid + 1, high);
// compare the two sub-arrays and return the common prefix
return commonPrefixUtil(str1, str2);
}
// in case of no common prefix, return an empty string
return "";
}
// helper method to compare two strings and find their common prefix
static String commonPrefixUtil(String str1, String str2) {
String result = "";
int n1 = str1.length(),
n2 = str2.length();
// compare characters at each index of the two strings
for (int i = 0, j = 0; i <= n1 - 1 && j <= n2 - 1; i++, j++) {
// if the characters are not the same, return the result
if (str1.charAt(i) != str2.charAt(j))
break;
// otherwise, add the character to the result
result += str1.charAt(i);
}
return (result);
}
public static void main(String[] args) {
// array of strings to find the common prefix
String[] arr = {"geeksforgeeks", "geeks", "geek", "geezer"};
int n = arr.length;
// call the commonPrefix method and store the result
String ans = commonPrefix(arr, 0, n - 1);
// print the result
if (ans.length() > 0) {
System.out.printf("The longest common prefix is - %s", ans);
} else {
System.out.printf("There is no common prefix");
}
}
}
OutputThe longest common prefix is - gee
Time complexity: O(NM log(N))
Auxiliary space: O(log(N))
Similar Reads
Java Program To Find Longest Common Prefix Using Sorting
Problem Statement: Given a set of strings, find the longest common prefix.Examples: Input: {"geeksforgeeks", "geeks", "geek", "geezer"} Output: "gee" Input: {"apple", "ape", "april"} Output: "ap" The longest common prefix for an array of strings is the common prefix between 2 most dissimilar strings
2 min read
How to Find the Longest Common Prefix of Two Strings in Java?
In this article, we will find the longest common prefix of two Strings in Java. Examples: Input: String 1= geeksforgeeks, String 2 = geezerOutput: âgeeâ Input: String 1= flower, String 2 = flightOutput: âflâ Methods to Find the Longest common Prefix of two Strings in JavaBelow are the methods by whi
4 min read
Longest Prefix Matching - A Trie Based Solution in Java
Given a dictionary of words and an input string, we need to find the longest prefix of the string that is also a word in the dictionary.Examples: Let the dictionary contain the following words:{are, area, base, cat, cater, children, basement}Below are the sample input/output:Input String Outputcater
4 min read
Java Program to Find Occurrence of a Word Using Regex
Java's regular expressions, or regex, let you do advanced text manipulation and matching. Regex offers a handy approach for searching for a term in a text wherever it appears. In this article, we will learn to find every occurrence of a word using regex. Program to Find Occurrence of a Word Using Re
2 min read
Java Program for Longest Common Subsequence
LCS Problem Statement: Given two sequences, find the length of longest subsequence present in both of them. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. For example, "abc", "abg", "bdf", "aeg", '"acefg", .. etc are subsequences of "abcdefg". So
4 min read
Java Program To Find Length Of The Longest Substring Without Repeating Characters
Given a string str, find the length of the longest substring without repeating characters. For âABDEFGABEFâ, the longest substring are âBDEFGAâ and "DEFGAB", with length 6.For âBBBBâ the longest substring is âBâ, with length 1.For "GEEKSFORGEEKS", there are two longest substrings shown in the below
8 min read
Java Program to Print Smallest and Biggest Possible Palindrome Word in a Given String
A Palindrome String is a string whose reversed string is equal to the original string. In this Java Program, we are going to see the approach of printing the smallest and biggest palindrome word in a String. Given a sentence of words in the form of a string, and we need to print the smallest and lon
3 min read
How to Check if a String Starts With One of Several Prefixes in Java?
Java programming provides a lot of packages for solving real-time problems. In our case, we need to check if a given string starts with one of several prefixes. For This first, we need to take one String value after that take some prefixes for testing if the String starts with one of several prefixe
2 min read
Java Program to Search a Particular Word in a String Using Regex
In Java string manipulation, searching for specific words is a fundamental task. Regular expressions (regex) offer a powerful and flexible approach to achieve this search. It matches the patterns simply by comparing substrings. In this article, we will learn how to search for a particular word in a
3 min read
Java Program to Find the Occurrence of Words in a String using HashMap
HashMap<Key, Value> provides the basic implementation of the Map interface of Java and import java.util.HashMap package or its superclass. HashMap stores the data in (Key, Value) pairs, and accessed by an index of another type (e.g. an Integer). One object is used as a key to another object. I
3 min read