Find the Length of the Longest Common Prefix - Problem
You are given two arrays arr1 and arr2 containing positive integers. Your task is to find the longest common prefix between any pair of numbers from these arrays.
A prefix of a positive integer is formed by taking one or more of its digits starting from the leftmost digit. For example:
123is a prefix of12345✅234is not a prefix of12345❌ (doesn't start from leftmost)
A common prefix exists between two numbers when they share the same starting digits. For example:
5655359and56554have common prefixes:5,56,565,56551223and43456have no common prefix
Goal: Find the length of the longest common prefix among all possible pairs (x, y) where x ∈ arr1 and y ∈ arr2.
Input & Output
example_1.py — Basic Case
$
Input:
arr1 = [1, 10, 100], arr2 = [1000]
›
Output:
3
💡 Note:
The longest common prefix is between 100 and 1000. They share the prefix "100" which has length 3.
example_2.py — Multiple Matches
$
Input:
arr1 = [1, 2, 3], arr2 = [4, 4, 4]
›
Output:
0
💡 Note:
There are no common prefixes between any pairs, so the answer is 0.
example_3.py — Complex Case
$
Input:
arr1 = [12345, 6789], arr2 = [123, 12, 1234567]
›
Output:
4
💡 Note:
The longest common prefix is between 12345 and 1234567, sharing "1234" with length 4.
Constraints
- 1 ≤ arr1.length, arr2.length ≤ 5 × 104
- 1 ≤ arr1[i], arr2[i] ≤ 108
- All numbers are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Create Directory Tree
Build a tree structure from the first contact list, where each level represents a digit position
2
Search for Matches
For each number in the second list, walk through the directory tree as far as you can go
3
Record Best Match
Keep track of the deepest level you reached - that's your longest common prefix!
Key Takeaway
🎯 Key Insight: By building a trie (directory tree) from one array, we can efficiently find the longest common prefix with any number from the second array in a single traversal, avoiding the need to compare every possible pair!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code