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)
1#include <vector>
2#include <string>
3#include <algorithm>
4
5using namespace std;
6
7int commonPrefixLength(const string& a, const string& b) {
8 int length = 0;
9 while (length < a.size() && length < b.size() && a[length] == b[length]) {
10 length++;
11 }
12 return length;
13}
14
15int longestCommonPrefix(vector<int>& arr1, vector<int>& arr2) {
16 int maxPrefix = 0;
17 for (const int& num1 : arr1) {
18 for (const int& num2 : arr2) {
19 maxPrefix = max(maxPrefix, commonPrefixLength(to_string(num1), to_string(num2)));
20 }
21 }
22 return maxPrefix;
23}
24
25int main() {
26 vector<int> arr1 = {1, 10, 100};
27 vector<int> arr2 = {1000};
28 cout << longestCommonPrefix(arr1, arr2) << endl;
29 return 0;
30}
This C++ approach similarly uses two nested loops to evaluate each pair of numbers. It determines the common prefix length of each pair by converting them to strings and comparing characters from the beginning, updating the maximum 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)
using System.Linq;
class Program {
public static int CommonPrefixLength(string a, string b) {
int i = 0;
while (i < a.Length && i < b.Length && a[i] == b[i]) {
i++;
}
return i;
}
public static int LongestCommonPrefix(int[] arr1, int[] arr2) {
Array.Sort(arr1);
Array.Sort(arr2);
int maxLength = 0;
foreach(var num1 in arr1) {
foreach(var num2 in arr2) {
int currLength = CommonPrefixLength(num1.ToString(), num2.ToString());
maxLength = Math.Max(maxLength, currLength);
}
}
return maxLength;
}
static void Main() {
int[] arr1 = {1, 10, 100};
int[] arr2 = {1000};
Console.WriteLine(LongestCommonPrefix(arr1, arr2));
}
}
The C# implementation enhances efficiency by sorting both arrays before checking for common prefixes. As comparisons are reduced to necessary ones, the overall execution speed benefits accordingly.