#3043

Find the Length of the Longest Common Prefix

specialist · 765 · lc medium +31 · verified · 57% accepted · 832 likes · top 52%

Description

You are given two arrays of positive integers arr1 and arr2.

A prefix of a positive integer is formed by one or more of its leading digits. For example, 123 is a prefix of 12345, but 234 is not.

A common prefix of two integers a and b is any integer that is a prefix of both.

Find the length of the longest common prefix among all pairs (x, y) with x from arr1 and y from arr2.

Return that length, or 0 if no common prefix exists.

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.

Code

1
2
3