class Solution(object):
def longestCommonPrefix(self, strs):
if not strs: return ''
first = min(strs)
for i in range(len(first)):
for s in strs:
if s[i] != first[i]:
return first[:i] if i > 0 else ''
return first
Simple Python solution using min()

@david120 min will return the alphabetically first string. I believe what you are trying here is to get the string with shortest length.

@blackPriest
Actually it does not matter for this problem. The first string alphabetically may not be the shortest one, but the for loop will always terminate if it encounters a letter not in the prefix, preventing the indexing error that I'm assuming you're worried about. For example, takestrs = ['aaa', 'ab']
. Even though'aaa'
is longer than'ab'
, the for loop will never reachi=2
, as it will terminate ati=1
. Of course if you changed themin(strs)
call tomin(strs, cmp=lambda x: len(x))
in order to get the shortest string as you suggest, it would work as well.

@david120 True, it will still give the right answer. I thought you are using the min() to get the shortest length string which will minimize the for loop running and reduce few (actually very few computation). So just pointed it out.

@david120 why do you want to find out alphbetically first string?