Find the Length of the Longest Common Prefix

Medium Topics Company Tags

Choose one integer from arr1 and one from arr2, and compare their decimal digits starting from the left. Return the greatest number of initial digits that match among all such pairs. If no pair starts with the same digit, return 0. The whole decimal representation of a number may be a prefix of another. Only pairs containing one element from each array count.

Example 1:

Input: arr1 = [456,12]
arr2 = [4599,8]

Output: 2

Explanation: The pair 456 and 4599 shares the initial digits 45, of length 2. No cross-array pair shares more initial digits.

Example 2:

Input: arr1 = [23]
arr2 = [2345]

Output: 2

Explanation: All digits of 23 match the beginning of 2345. The common prefix is 23 and has length 2.

Example 3:

Input: arr1 = [7,89]
arr2 = [10,66]

Output: 0

Explanation: Every number in the first array starts with 7 or 8, while every number in the second starts with 1 or 6. No first digit matches, so return 0.

Constraints:

  • 1 <= arr1.length, arr2.length <= 50000
  • 1 <= arr1[i], arr2[i] <= 100000000


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.