Find the Length of the Longest Common Prefix Problem
Description
LeetCode Problem 3043.
You are given two arrays with positive integers arr1 and arr2.
A prefix of a positive integer is an integer formed by one or more of its digits, starting from its leftmost digit. For example, 123 is a prefix of the integer 12345, while 234 is not.
A common prefix of two integers a and b is an integer c, such that c is a prefix of both a and b. For example, 5655359 and 56554 have common prefixes 565 and 5655 while 1223 and 43456 do not have a common prefix.
You need to find the length of the longest common prefix between all pairs of integers (x, y) such that x belongs to arr1 and y belongs to arr2.
Return the length of the longest common prefix among all pairs. If no common prefix exists among them, return 0.
Example 1:
Input: arr1 = [1,10,100], arr2 = [1000]
Output: 3
Explanation: There are 3 pairs (arr1[i], arr2[j]):
- The longest common prefix of (1, 1000) is 1.
- The longest common prefix of (10, 1000) is 10.
- The longest common prefix of (100, 1000) is 100.
The longest common prefix is 100 with a length of 3.
Example 2:
Input: arr1 = [1,2,3], arr2 = [4,4,4]
Output: 0
Explanation: There exists no common prefix for any pair (arr1[i], arr2[j]), hence we return 0.
Note that common prefixes between elements of the same array do not count.
Constraints:
1 <= arr1.length, arr2.length <= 5 * 10^41 <= arr1[i], arr2[i] <= 10^8
Solution
Approach: Hash Set of Prefixes
Put every prefix of every number in arr1 into a hash set (a number with d digits has d prefixes, got by repeatedly dividing by 10). Then, for each x in arr2, try its prefixes from the longest to the shortest; the first one found in the set is the best common prefix for x, so update the answer with its digit count and move on to the next number.
Complexity: time O(n log M + m log N), space O(n log M), where n and m are the lengths of arr1 and arr2, and M and N their maximum values.
class Solution:
def longestCommonPrefix(self, arr1: List[int], arr2: List[int]) -> int:
s = set()
for x in arr1:
while x:
s.add(x)
x //= 10
mx = 0
for x in arr2:
while x:
if x in s:
mx = max(mx, x)
break
x //= 10
return len(str(mx)) if mx else 0