Find the Length of the Longest Common Prefix

Medium

Topics
ArrayHash TableStringTrie

You are given two arrays of positive integers, a and b.

A common prefix of two integers is a prefix they share when both are written in decimal with no leading zeros: 5655359 and 56554 share 565, which has length 3, while 1223 and 43456 share nothing.

Return the length of the longest common prefix over all pairs (x, y) with x from a and y from b, or 0 if no pair shares a prefix.

Example 1

a110100
b1000
shared100
the best-matching pair
A prefix here is a prefix of the decimal digits, so 100 counts as a prefix of 1000 even though it is a smaller number. The shaded pair 100 and 1000 share 3 digits, and no other pair shares more.
The two rows are the two input arrays; they have independent lengths.
Input:  a = [1,10,100], b = [1000]
Output: 3
Explanation: 100 and 1000 share the prefix 100. The pair (10, 1000) shares only 10, and (1, 1000) only 1.

Example 2

a123
b444
No pair here shares even a first digit, so the answer is 0.
Input:  a = [1,2,3], b = [4,4,4]
Output: 0
Explanation: No number in a starts with a 4, so no pair shares even one digit.

Example 3

a1
b1
shared1
the best-matching pair
Input:  a = [1], b = [1]
Output: 1
Explanation: The two numbers are equal, so the whole of one is a prefix of the other.

Constraints

  • 1 <= a.length, b.length <= 5 * 10^4
  • 1 <= a[i], b[i] <= 10^8
Editorial — intuition, approach, complexity and pitfalls

Intuition

Comparing every pair digit by digit is the obvious route and it does the same work repeatedly: if three numbers in a all start with 12, each of them re-establishes that fact against every number in b.

The way out is to stop thinking about pairs. Collect every prefix of every number in a into a set — for 100 that is 1, 10 and 100. Then for each number in b, walk its own prefixes from the shortest up and ask whether the set contains them. The longest hit is that number’s best, and the answer is the largest over all of b.

This is cheap because a number under 10^8 has at most 9 prefixes, so the set holds at most 9 entries per element of a and each element of b costs at most 9 lookups. A trie expresses the same idea with less memory, and the set version is the one worth reaching for first.

Approach

  1. Build a set of every prefix of every number in a. Generate a number’s prefixes by repeatedly dividing it by 10 — or by taking the prefixes of its decimal string.
  2. For each number in b, take its prefixes in increasing length and check each against the set.
  3. Track the length of the longest prefix found in the set across all of b.
  4. Return 0 if nothing matched, which falls out of initialising the best length to 0.

Walkthrough

a = [1, 10, 100]
b = [1000]

prefixes of a
     1   -> 1
    10   -> 1, 10
   100   -> 1, 10, 100
  set = {1, 10, 100}

prefixes of 1000, shortest first
     1    in the set   length 1
    10    in the set   length 2
   100    in the set   length 3
  1000    not in set   stop looking

answer 3

Complexity

  • Time — O((n + m) * d): d is the digit count, at most 9 here, so this is linear in the inputs for every practical purpose. The pairwise comparison is O(n * m * d).
  • Space — O(n * d): the prefix set holds at most one entry per digit of each element of a.

Common Pitfalls

  • Returning the longest prefix for the first matching pair rather than the maximum over all pairs.
  • Stopping at the first prefix of a number in b that is absent. That is a valid shortcut — if 12 is not a prefix then neither is 123 — but only because prefixes are nested; applying the same logic across different numbers is not valid.
  • Comparing the numbers rather than their digit strings: 100 is not numerically a prefix of 1000, it is a textual one.
  • Treating a number as a prefix of a shorter number. 1000 and 100 share 3 digits, not 4.

Full Solution — all languages

class Solution:
    def longestCommonPrefix(self, a, b):
        prefixes = set()
        for value in a:
            while value:
                prefixes.add(value)
                value //= 10
        best = 0
        for value in b:
            text = str(value)
            for length in range(1, len(text) + 1):
                if int(text[:length]) in prefixes:
                    best = max(best, length)
        return best
SensAI
Beta
Tap the mic to stop voice mode