Link: 14. Longest Common Prefix - easy

Question

Restate the problem

  • Find the longest common prefix among the strings

Edge Case

  • Empty input list

Method 1 compare the whole prefix
Method 2 horizontal scanning with pointers

Method

Approach

  • Pick first word as a reference
  • Compare characters column by column across all strings
  • Stop at first mismatch

Complexity

  • Time Complexity: O()
    • m = length of the shortest word
    • n = number of strings
  • Space Complexity: O(1)

Code

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs:
            return ""
        
        min_length = min(len(word) for word in strs)
        p = 0
        while p < min_length:
            char = strs[0][p]
            for word in strs:
                if char != word[p]:
                    return strs[0][:p]
            
            p += 1
        
        return strs[0][:p]

History

Jan-23-2026 Hinted

  • only need min_length
  • don’t know how to cal the min_length
  • min_len = min(len(word) for word in strs)

Jan-19-2026 Solved, need clear explanation