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: 3
💡 Note: The longest common prefix is between 100 and 1000: "100" has length 3

Constraints

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

Visualization

Tap to expand
Longest Common Prefix Length INPUT arr1 1 10 100 arr2 1000 Prefix Examples: 1 --> "1" 10 --> "1", "10" 100 --> "1", "10", "100" 1000 --> "1", "10", "100", "1000" arr1=[1,10,100], arr2=[1000] ALGORITHM STEPS 1 Build Prefix Set Store all prefixes of arr1 2 HashSet Content {"1", "10", "100"} 3 Check arr2 Prefixes Match against set 4 Track Max Length Return longest match Prefix Matching for 1000: "1" FOUND len=1 "10" FOUND len=2 "100" FOUND len=3 "1000" NOT FOUND Max Length = 3 FINAL RESULT Longest Common Prefix: "100" Length = 3 Best Matching Pair: 100 from arr1 & 1000 from arr2 Common prefix "100" found in both numbers Output: 3 Key Insight: Using a HashSet to store all prefixes from arr1 allows O(1) lookup time when checking prefixes of arr2 elements. This reduces time complexity from O(n*m*d^2) brute force to O(n*d + m*d) where d is the max digit count. Space trade-off for speed efficiency. TutorialsPoint - Find the Length of the Longest Common Prefix | Hash Set Approach
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