Find the Length of the Longest Common Prefix

You are given two arrays of **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 `12345`, while `234` is not. A **common prefix** of two integers `a` and `b` is an integer `c` that is a prefix of both `a` and `b`. For example, `5655359` and `56554` have common prefixes `565` and `5655`, while `1223` and `43456` have none. Find the length of the **longest common prefix** among all pairs `(x, y)` with `x` from `arr1` and `y` from `arr2`. Return *the length of the longest common prefix among all pairs*. If no common prefix exists among them, return `0`.

30:00

Find the Length of the Longest Common Prefix
medium
Free written solution
Topics
Companies

You are given two arrays of 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 12345, while 234 is not.

A common prefix of two integers a and b is an integer c that is a prefix of both a and b. For example, 5655359 and 56554 have common prefixes 565 and 5655, while 1223 and 43456 have none.

Find the length of the longest common prefix among all pairs (x, y) with x from arr1 and y from 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
Constraints:
  • 1≤arr1.length,arr2.length≤5×1041 \leq \text{arr1.length}, \text{arr2.length} \leq 5 \times 10^4

  • 1≤arr1[i],arr2[i]≤1081 \leq \text{arr1}[i], \text{arr2}[i] \leq 10^8

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"arr1":[1,10,100],"arr2":[1000]}

Put every number of arr1 into a trie, one digit per edge. Then each number of arr2 walks down that trie, and the depth it reaches is its longest common prefix with anything in arr1.

arr1 (goes into the trie)

1
10
100

arr2 (walks the trie)

1000

digit trie of arr1 (0 nodes)

·

depth

-

best

0

best prefix

-

inserting from arr1
arr2 walk
missing edge
deepest match so far
Variables
VariableValue
best0
DepthFunction Call
Stack empty
0/10