14. Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

Method 1 Scan from shortest word (S (total number of characters in the array) time, 1 space)

  • Traverse the array and get the shortest string.
  • Traverse each character from the shortest string again the character at the same index in all other strings, check if they are the same.
def LCP(self, strs):
    if not strs:
        return ""
    shortest = min(strs, key=len)
    for i, char in enumerate(shortest):
        for other in strs:
            if other[i] != ch:
                return shortest[:i]
    return shortest

results matching ""

    No results matching ""