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:

  • 123 is a prefix of 12345
  • 234 is not a prefix of 12345 ❌ (doesn't start from leftmost)

A common prefix exists between two numbers when they share the same starting digits. For example:

  • 5655359 and 56554 have common prefixes: 5, 56, 565, 5655
  • 1223 and 43456 have 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
Phone Directory: Finding Longest Matching PrefixesContact List 1: [555-1234, 555-5678]555-1234555-5678Contact List 2: [555-9999]555-9999Step 1: Build Directory Tree from List 1📞555555Step 2: Search 555-9999 in tree📞5559Match found!Path: 5→5→5Length: 3✗ '9' not foundStop here🎯 Result:Longest matching prefix:"555" with length 3Found between any 555-xxxx numbers!
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!
Asked in
Google 42 Amazon 38 Meta 25 Microsoft 31
23.8K Views
Medium-High Frequency
~18 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen