⚡Flashcard Drill➔
NeetCode #155LC-3043MediumArrays & Hashing
← Back to All Problems

#155 · #3043 · Find the Length of the Longest Common Prefix(最长公共前缀的长度)

📌 Problem Statement & Constraints

You are given two arrays of positive integers arr1 and arr2. For each pair of integers, consider their decimal string representations. Return the length of the longest common prefix among all such pairs. Constraints: 1 <= arr1.length, arr2.length <= 5 * 10^4, 1 <= arr1[i], arr2[i] <= 10^8.

💡 Core Algorithmic Approaches

  1. Insert every prefix of every number in arr1 into a hash set.
  2. For each number in arr2, extend its prefix character by character and stop as soon as the prefix is not in the set.
  3. Track the maximum matched length across all of arr2.
  4. The early break matters: once a prefix fails, every longer prefix also fails.

💻 Benchmark Python3 Implementation

class Solution:
    def longestCommonPrefix(self, arr1: List[int], arr2: List[int]) -> int:
        prefixes = set()
        for x in arr1:
            s = str(x)
            for i in range(1, len(s) + 1):
                prefixes.add(s[:i])        # every prefix of every number
        res = 0
        for x in arr2:
            s = str(x)
            for i in range(1, len(s) + 1):
                if s[:i] in prefixes:
                    res = max(res, i)
                else:
                    break                  # longer prefixes cannot match either
        return res

⚡ Complexity Deep Dive

⏱️ Time Complexity
O((n + m) * L) where L is the maximum number of digits (9 here), since each prefix is inserted or looked up once.
💾 Space Complexity
O(n * L) for the prefix set.

⚠️ Interview Pitfalls & Follow-ups

  • Comparing numbers numerically: the problem is about the decimal string prefix, so 123 and 12 share the prefix "12" of length 2, not the numeric prefix.
  • Forgetting the early break: it is not required for correctness but avoids pointless lookups.
  • Storing full numbers instead of prefixes: the lookup would then require checking all possible prefix lengths anyway, defeating the purpose.
  • Using a trie: also correct and O(n * L) in both time and space, but more code than the prefix-set approach for the small L here.
⚡
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

中文速览与面试要点

最长公共前缀的长度

给你两个正整数数组 arr1 和 arr2。请你从 arr1 和 arr2 中各选出一个整数,并找出能够同时整除这两个整数的 最长公共前缀 的长度。换言之,找出最长的整数 x,使得 arr1 中某个数的十进制表示以 x 开头,arr2 中某个数的十进制表示也以 x 开头。返回这个最长前缀的长度。如果不存在公共前缀,返回 0。约束:1 ≤ arr1.length, arr2.length ≤ 5 × 10^4;1 ≤ arr1[i], arr2[i] ≤ 10^8。

核心要点

  • 哈希集合存前缀(标准解) :把 arr1 中每个数的 所有 前缀(长度 1 到 len(s))加入集合。
  • 校验 arr2 :对 arr2 中每个数,从长到短检查它的前缀是否在集合中,取最大长度。
  • 为什么用集合而非 Trie :数字的字符串长度最多 9,直接枚举所有前缀的规模很小(每个数 ≤ 9 个前缀),哈希集合实现更简洁。
  • 优化 :可以只记录「集合中出现过的最大前缀长度」,并在 arr2 校验时从该长度往下试,减少无效检查。

常见陷阱

  • 只把每个数的完整值加入集合 :那是求「是否存在相同的数」,不是求公共前缀。必须加入所有前缀。
  • 把前缀当整数存 :前导零会丢失(虽然本题正整数无前导零,但用字符串更直观且安全)。
  • 忘记返回 0 :不存在公共前缀时应返回 0(例如 arr1 = [1]、arr2 = [2])。
  • 用 Trie 过度设计 :本题数字位数极少,哈希集合已足够,Trie 会引入不必要的复杂度。

参考实现

class Solution:
    def longestCommonPrefix(self, arr1: list[int], arr2: list[int]) -> int:
        prefixes = set()
        for x in arr1:
            s = str(x)
            for i in range(1, len(s) + 1):
                prefixes.add(s[:i])

        best = 0
        for x in arr2:
            s = str(x)
            for i in range(1, len(s) + 1):
                if s[:i] in prefixes:
                    if i > best:
                        best = i
        return best