Intuition
Convert each number to a string and compare character by character for every pair across the two arrays, tracking the longest matching prefix.
Explanation
Approach
- For every pair
(x, y)withxfromarr1andyfromarr2:- Convert both to strings.
- Compare characters from the left; count how many match before the first difference.
- Track the global maximum prefix length.
Complexity
- Time:
O(n * m * d)wheren,mare array lengths anddis the max number of digits (up to 9). Withn, m = 5*10^4, this is up to ~2.25 * 10^9 -- too slow. - Space:
O(d)for the string conversions.
Implementation
class Solution {
public int longestCommonPrefix(int[] arr1, int[] arr2) {
int result = 0;
for (int x : arr1) {
for (int y : arr2) {
String sx = String.valueOf(x);
String sy = String.valueOf(y);
int length = 0;
for (int i = 0; i < Math.min(sx.length(), sy.length()); i++) {
if (sx.charAt(i) != sy.charAt(i)) break;
length++;
}
result = Math.max(result, length);
}
}
return result;
}
}