Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".

Link of problem: https://leetcode.com/problems/longest-common-prefix/

Algorithm

  1. Sort the array of strings in alphabetical order.

  2. Compare the characters in the first and last strings in the array. Since the array is sorted, common characters among the first and last element will be common among all the elements of the array.

    2.1. If they are same, then append the character to the result.

    2.2. Else, stop the comparison – result contains the longest common prefix among the strings in the array.

The below diagram showing how the algorithm works

problem1-step1
problem1-step2
problem1-step3
problem1-step4
previous arrow
next arrow
problem1-step1
problem1-step2
problem1-step3
problem1-step4
previous arrow
next arrow
 

Java Code

Source: https://www.educative.io/edpresso/how-to-find-the-longest-common-prefix-in-an-array-of-strings

Be the first to comment

Leave a Reply

Your email address will not be published.


*