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)
1def common_prefix_length(a: str, b: str) -> int:
2 i = 0
3 while i < len(a) and i < len(b) and a[i] == b[i]:
4 i += 1
5 return i
6
7
8def longest_common_prefix(arr1, arr2):
9 max_length = 0
10 for num1 in arr1:
11 for num2 in arr2:
12 str1 = str(num1)
13 str2 = str(num2)
14 curr_length = common_prefix_length(str1, str2)
15 max_length = max(max_length, curr_length)
16 return max_length
17
18
19arr1 = [1, 10, 100]
20arr2 = [1000]
21print(longest_common_prefix(arr1, arr2))
22
This Python solution iterates through each pair of integers from the input arrays, converting them to strings for prefix comparison. It keeps track of and returns the length of the longest common prefix found.
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 C solution uses sorting to increase the efficiency of comparisons. Once the arrays are sorted, potential longer common prefixes only appear among consecutive elements, reducing unnecessary computations and leading to quicker results.