Write a function longestCommonPrefix
that takes in an array of strings and returns the longest common prefix among them. If there is no common prefix, the function should return an empty string.
For example, given the array ["flower", "flow", "flight"]
, the function should return "fl"
because that is the longest common prefix among these strings. Similarly, given the array ["dog", "racecar", "car"]
, the function should return an empty string.
Implementation of longestCommonPrefix
should be done using string manipulation techniques.
To solve this problem, we can iterate through the characters of the strings starting from the first character and check if that character is common in all the strings. If it is, we append it to the common prefix. We keep repeating this process for all the characters until we find a character that is not common in all the strings or we reach the end of any string.
Here's the step-by-step detailed explanation of the solution:
strs
is empty. If it is, there are no strings to compare, so we return an empty string.commonPrefix
variable as an empty string. This variable will store the longest common prefix found so far.strs
array using a for
loop.char
.for
loop to iterate through all the strings in the strs
array starting from the second string (index 1).char
is equal to the character at the same index in the current string. If they are not equal, we break the loop and return the commonPrefix
as it is, which will be the longest common prefix found so far.char
is equal to the character at the same index in all the strings, we append it to the commonPrefix
string.commonPrefix
string, which will be the longest common prefix among all the strings in the input array.def longestCommonPrefix(strs):
if not strs: # Check if input array is empty
return ""
commonPrefix = ""
for i in range(len(strs[0])): # Iterate through characters of the first string
char = strs[0][i] # Current character of the first string
for j in range(1, len(strs)): # Iterate through all other strings
if i >= len(strs[j]) or strs[j][i] != char: # Check if character is not common
return commonPrefix
commonPrefix += char # Append common character to commonPrefix
return commonPrefix # Return commonPrefix if all characters are common
The time complexity of this solution is O(N*M), where N is the length of the array strs
and M is the average length of the strings. In the worst case scenario, we have to iterate through all the characters of the longest string in the array.