top of page

Longest Common Prefix

  • Shreyas Naphad
  • Jun 17, 2024
  • 1 min read

In this article, we will solve the problem of finding the longest common prefix among an array of strings.


Problem Statement:

Find the longest common prefix (LCP) among all the strings. If there is no common prefix, return an empty string.


Example 1:

Input: s = ["flower","flow","flight"]

Output: "fl"

Explanation: The longest common prefix is "fl".

Example 2:

Input: s = ["dog","mouse","car"]

Output: ""

Explanation: There is no common prefix among the input strings

 

Solution Approach:

To solve this problem, we will use the following approach:

1.    Handle Edge Cases:

o   If the input array is empty, return an empty string.

o   If the input array contains only one string, return that string as the longest common prefix.

2.    Find the Shortest String:

o   The longest common prefix cannot be longer than the shortest string in the array. Therefore, first identify the shortest string.

3.    Compare Characters:

o   Compare characters of the shortest string with the corresponding characters of all other strings in the array.

o   If a mismatch is found, return the substring from the beginning to the mismatched character.



Time Complexity:  O(S), where S is the sum of all characters in all strings.

Space Complexity: O(1)

Comentários


©2025 by DevSparks.

bottom of page