Sponsored
Sponsored
The simplest way to solve this problem is to iterate over each pair of integers from arr1 and arr2. For each pair, convert the integers to strings and compare character by character to find the common prefix. Keep a running maximum of the lengths of these prefixes.
Since we are comparing each pair, the time complexity is O(n * m * k), where n is the length of arr1, m is the length of arr2, and k is the length of the longest number when converted to a string. Space complexity is O(1) as we're only storing a few additional variables.
Time complexity: O(n * m * k), Space complexity: O(1)
1public class LongestCommonPrefix {
2
3 public static int commonPrefixLength(String a, String b) {
4 int i = 0;
5 while (i < a.length() && i < b.length() && a.charAt(i) == b.charAt(i)) {
6 i++;
7 }
8 return i;
9 }
10
11 public static int longestCommonPrefix(int[] arr1, int[] arr2) {
12 int maxLength = 0;
13 for (int num1 : arr1) {
14 for (int num2 : arr2) {
15 String str1 = Integer.toString(num1);
16 String str2 = Integer.toString(num2);
17 int currLength = commonPrefixLength(str1, str2);
18 maxLength = Math.max(maxLength, currLength);
19 }
20 }
21 return maxLength;
22 }
23
24 public static void main(String[] args) {
25 int[] arr1 = {1, 10, 100};
26 int[] arr2 = {1000};
27 System.out.println(longestCommonPrefix(arr1, arr2));
28 }
29}
30
This Java solution uses nested loops to iterate through every pair of numbers from the two arrays. It calculates the common prefix length by converting the numbers to strings and matching characters until they differ, updating the maximum prefix length.
This optimized approach leverages sorting of the input arrays to reduce comparisons. After sorting, only consecutive elements can potentially have a longer common prefix with elements of the other array than already found max. This minimizes the number of comparisons, improving efficiency over the brute force approach.
Time complexity may approach O(n + m) in the best-case scenario where common prefixes are found early, but in the worst case it remains approximately O(n * m). The space complexity is still O(1).
Average Time complexity: O(n log n + m log m + n + m), Space complexity: O(1)
This Python solution features sorting of input arrays for efficient prefix checks. Only necessary comparisons are executed, speeding up computation relative to the unsorted method.