Find the Length of the Longest Common Prefix - Problem

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

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

You need to find the length of the longest common prefix between all pairs of integers (x, y) such that x belongs to arr1 and y belongs to arr2.

Return the length of the longest common prefix among all pairs. If no common prefix exists among them, return 0.

Input & Output

Example 1 — Basic Case
$ Input: arr1 = [1,10,100], arr2 = [1000]
Output: 3
💡 Note: The longest common prefix is between 100 and 1000: "100" has length 3
Example 2 — Multiple Matches
$ Input: arr1 = [1,2,3], arr2 = [4,4,4]
Output: 0
💡 Note: No common prefixes exist between any pairs, so return 0
Example 3 — Single Digit Match
$ Input: arr1 = [1,10,100], arr2 = [1000,2000]
Output: 1
💡 Note: Multiple numbers share prefix "1" but that's the longest common prefix with length 1

Constraints

  • 1 ≤ arr1.length, arr2.length ≤ 5 × 104
  • 1 ≤ arr1[i], arr2[i] ≤ 108

Visualization

Tap to expand
Find Longest Common Prefix Lengtharr1 = [1, 10, 100]110100arr2 = [1000]1000100 ↔ 1000Common prefix: "100"Check all pairs for common prefixes:1↔1000: "1" (length 1)10↔1000: "1" (length 1)100↔1000: "100" (length 3) ← MaximumOutput: 3
Understanding the Visualization
1
Input Arrays
Two arrays of positive integers
2
Compare Prefixes
Find common prefixes between pairs from both arrays
3
Return Maximum
Length of the longest common prefix found
Key Takeaway
🎯 Key Insight: Convert numbers to strings and systematically compare prefixes to find the maximum common length
Asked in
Google 15 Amazon 12 Meta 8
8.5K Views
Medium Frequency
~25 min Avg. Time
320 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