Longest Common Prefix in an array of Strings in java

Last updated on March 14th, 2017 at 12:20 pm

Previous
Next

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:

Previous
Next

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog