⚡Flashcard Drill➔
NeetCode #38LC-14EasyArrays & HashingNC 250
← Back to All Problems

#38 · #14 · Longest Common Prefix(最长公共前缀)

📌 Problem Statement & Constraints

Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return the empty string "". Constraints: 1 <= strs.length <= 200, 0 <= strs[i].length <= 200; strings contain only lowercase English letters.

💡 Core Algorithmic Approaches

  1. Vertical scanning: compare the character at position i across all strings. As soon as any string is too short or disagrees, the prefix ends at i.
  2. This is O(S) where S is the total number of characters -- optimal, since you must read the input.
  3. Alternative (elegant): sort the strings. The common prefix of the whole array equals the common prefix of the first and last strings after sorting.
  4. The sorted variant is short but costs O(n log n) comparisons, so vertical scanning is the better answer when asked about complexity.

💻 Benchmark Python3 Implementation

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs:
            return ""
        first = strs[0]
        for i in range(len(first)):
            ch = first[i]
            for s in strs[1:]:
                # string too short, or character mismatch -> prefix ends here
                if i == len(s) or s[i] != ch:
                    return first[:i]
        return first


# Sorted variant: O(n log n) comparisons but only one string comparison
class Solution2:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs:
            return ""
        strs = sorted(strs)
        a, b = strs[0], strs[-1]
        i = 0
        while i < len(a) and i < len(b) and a[i] == b[i]:
            i += 1
        return a[:i]

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(S) for vertical scanning, where S is the sum of all string lengths -- each character is examined at most once. The sorted variant is O(n log n * k) in the worst case due to string comparisons.
💾 Space Complexity
O(1) extra space for vertical scanning; the sorted variant allocates a sorted copy, so O(n) extra.

⚠️ Interview Pitfalls & Follow-ups

  • Indexing without the length guard: s[i] raises IndexError when a string is shorter than the current prefix position. The check i == len(s) must come first.
  • Assuming all strings are non-empty: the constraints allow strs[i].length == 0, in which case the answer is immediately "" -- the guard above handles it.
  • Starting from the longest string: always iterate over strs[0], since the prefix cannot be longer than any string.
  • Forgetting the strs empty case: LeetCode guarantees strs.length >= 1, but defensive code costs nothing and the sorted variant needs it if you slice.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""。约束:1 ≤ strs.length ≤ 200;0 ≤ strs[i].length ≤ 200;strs[i] 仅由小写英文字母组成。

核心要点

  • 纵向扫描(推荐) :以第一个字符串为基准,逐列比较所有字符串的第 i 个字符。一旦某个字符串长度不足 i,或字符与基准不一致,则前 i 个字符即为答案。
  • 横向扫描 :维护当前公共前缀 prefix,依次与每个字符串求公共前缀并更新。实现直观,但每次比较都要重新扫一遍 prefix。
  • 分治法 :把数组二分,分别求左右半区的最长公共前缀,再取二者的公共前缀。时间同为 O(S),但常数更大,仅在需要并行时有价值。
  • 复杂度记号 :设 S 为所有字符串的字符总数,m 为最短字符串长度,n 为字符串个数。纵向扫描最坏为 O(n · m),不超过 O(S)。

常见陷阱

  • 忘记处理空数组 :strs 可能为空吗?本题约束保证长度 ≥ 1,但生产代码仍应防御性返回空串。
  • 漏掉「某个字符串比基准短」的分支 :只比较字符相等而忘记 i &gt;= len(other) ,会抛 IndexError。这是本题最常见的运行时错误。
  • 误用「最短串作为基准」 :以最短串为基准也是正确的(前缀不可能超过最短串),但以第一个串为基准 + 边界判断同样正确,且无需先求最短。
  • 被追问「两两求前缀」的复杂度 :若对 n 个字符串反复两两合并,最坏会退化为 O(n · m) 的常数更大的版本;纵向扫描是更优写法。

参考实现

class Solution:
    def longestCommonPrefix(self, strs: list[str]) -> str:
        if not strs:
            return ''
        first = strs[0]
        for i, ch in enumerate(first):
            for other in strs[1:]:
                # other 太短,或该位置字符不匹配 -> 前缀到此为止
                if i >= len(other) or other[i] != ch:
                    return first[:i]
        return first        # 第一个字符串整体就是公共前缀