## Similar Problems

Similar Problems not available

# Find The String With Lcp - Leetcode Solution

## Companies:

LeetCode: Find The String With Lcp Leetcode Solution

Difficulty: Hard

Topics: greedy dynamic-programming union-find string matrix array

Problem statement:

Given a list of strings, find the string with the longest common prefix (LCP).

Example 1:

Input: ["flower","flow","flight"] Output: "fl"

Example 2:

Input: ["dog","racecar","car"] Output: ""

Explanation: There is no common prefix among the input strings.

Solution:

We can solve this problem by using the concept of Longest Common Prefix (LCP). For two strings, the LCP is the longest prefix that is common to both strings. For example, the LCP of "flower" and "flow" is "fl".

To find the LCP of a list of strings, we can start with the first string and compare it with all the other strings in the list. For each comparison, we can update the LCP to be the common prefix of the two strings. If we find that the LCP becomes an empty string, we can stop comparing and return the empty string as the result since there is no common prefix among the input strings.

Let's implement this algorithm in Python:

def longest_common_prefix(strs): if not strs: # check if the input list is empty return "" lcp = strs[0] # initialize LCP to the first string in the list for s in strs[1:]: # iterate over all other strings in the list i = 0 # initialize index to 0 while i < len(lcp) and i < len(s): # compare the characters of the strings if lcp[i] != s[i]: # if the characters do not match, break the loop break i += 1 # update index lcp = lcp[:i] # update LCP to be the common prefix of the two strings if not lcp: # if LCP becomes an empty string, return the empty string return "" return lcp # return the LCP

Let's test the function with some examples:

print(longest_common_prefix(["flower","flow","flight"]))

# Output: "fl"

print(longest_common_prefix(["dog","racecar","car"]))

# Output: "" (empty string)

print(longest_common_prefix(["apple","ape","apricot"]))

# Output: "ap"

print(longest_common_prefix([]))

# Output: "" (empty string)

Time complexity: The time complexity of the above implementation is O(n*m), where n is the number of strings in the input list and m is the length of the longest string. We are iterating over all the strings in the list and comparing each character of the strings until we find a mismatch or reach the end of the string. The worst-case scenario is when all the strings are the same and have length m, which results in a total of n*(m+m) comparisons.

Space complexity: The space complexity of the above implementation is O(1), which is constant since we are only using some variables to store the input strings and the LCP. We are not using any additional space to solve this problem.

## Find The String With Lcp Solution Code

`1`