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)
1function commonPrefixLength(a, b) {
2 let i = 0;
3 while (i < a.length && i < b.length && a[i] === b[i]) {
4 i++;
5 }
6 return i;
7}
8
9function longestCommonPrefix(arr1, arr2) {
10 let maxLength = 0;
11 for (const num1 of arr1) {
12 for (const num2 of arr2) {
13 const str1 = num1.toString();
14 const str2 = num2.toString();
15 const currLength = commonPrefixLength(str1, str2);
16 maxLength = Math.max(maxLength, currLength);
17 }
18 }
19 return maxLength;
20}
21
22const arr1 = [1, 10, 100];
23const arr2 = [1000];
24console.log(longestCommonPrefix(arr1, arr2));
25
This JavaScript solution applies nested loops to check every pair of numbers from the arrays. It calculates the common prefix length by comparing string characters and stores the maximum found value.
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 Java approach sorts both input arrays to efficiently locate common prefixes. By focusing on sorted sequences, prefix comparisons are reduced, often resulting in early termination through optimal comparisons.