Longest Common Prefix in an array of Strings in java

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.

In this post, we are going to see longest common prefix in array of Strings.
So lets say you have string array as below:

So Longest common prefix in above String array will be “java” as all above string starts with “java”.
Lets take one more example:

So Longest common prefix in above String array will be “sql” as all above string starts with “sql”.

Algorithm:

  • Find minimum length String.
  • Iterate over array of String and if we find any mismatch with minimum length String, we break the loop and that index will give us longest common prefix of this array of String,

Java Program to find Longest Common Prefix:

Create a main Class called LongestCommonPrefixMain.java.
When you run above program, you will get below output:

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *