Simple Python solution using min()

  • 3
    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

  • 0

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

  • 0

    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, take strs = ['aaa', 'ab']. Even though 'aaa' is longer than 'ab', the for loop will never reach i=2, as it will terminate at i=1. Of course if you changed the min(strs) call to min(strs, cmp=lambda x: len(x)) in order to get the shortest string as you suggest, it would work as well.

  • 0

    @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.

  • 0

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

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.