Easy approach with O(n) time complexity in python


#1
class Solution:

@param A : list of strings

@return a strings

def longestCommonPrefix(self, A):
A.sort()
c = “”
if len(A[0]) > len(A[-1]):
a = A[0]
b = A[-1]
else:
b = A[0]
a = A[-1]
for i in range(len(b)):
if a[i] == b[i]:
c += a[i]

return c

#2

Your Solution is still nlogn. instead of sorting, you can find max and min

class Solution:
# @param A : list of strings
# @return a strings
def longestCommonPrefix(self, A):
mn = A[0]
mx = A[0]
for i in range(1,len(A)):
mn = min(mn,A[i])
mx = max(mx,A[i])

    c = ""
    if len(mn) > len(mx):
        a = mn
        b = mx
    else:
        b = mn
        a = mx
    for i in range(len(b)):
        if a[i] == b[i]:
            c += a[i]
    return c