Find Longest Common Prefix in an Array of Strings

How to find longest common prefix in an array of strings.

Given an array of strings, write a method to find the longest common prefix string. If no common prefix is found, return an empty string ” “.

For example:

Example 1:

Input: [“cat”,”cable”,”camera”]
Output: “ca”

The longest common prefix is ca.

Example 2:

Input: [“rat”,”dog”,”elephant”]
Output: “”

No common prefix is found.

In this tutorial, I am going to discuss the algorithm and their java implementation to find the longest common prefix amongst an array of strings.

Longest Common Prefix

Longest Common Prefix

Programming Tutorials

Find First Non-repeating character in a string

Find Longest Common Prefix in an Array of Strings – Java Code

To understand this, let’s suppose there are two strings cat and cable. What’s the longest common prefix in both of them? It’s ca.

Let’s take the third word camera into the consideration. After that, still the longest common prefix is ca.

To solve this, let’s assume the string present at 0th index is the longest common prefix so far. After that take the next string and compare with the LCP so far.

We have to compare the each character of the current string with longest common prefix string found so far. After the complete iteration, the final result will be our longest common prefix of all the strings.

Longest common prefix video tutorial

Longest Common Prefix LeetCode Solution

Check whether two strings are anagram of each other

Most Popular Data Structure Books

Data structure made easy

Cracking the coding interview

Tagged , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.