3043. Find the Length of the Longest Common Prefix
</> Solution
/**
* Problem: LeetCode 3043 - Find the Length of the Longest Common Prefix
* Difficulty: Medium
* Language: Java
* Author: CodeByTushu
*/
import java.util.HashSet;
import java.util.Set;
class Solution {
public int longestCommonPrefix(int[] arr1, int[] arr2) {
Set<Integer> prefixes = new HashSet<>();
// Store all numerical prefixes of numbers in arr1
for (int val : arr1) {
while (val > 0) {
prefixes.add(val);
val /= 10;
}
}
int maxLength = 0;
// Check prefixes of numbers in arr2 starting from longest to shortest
for (int val : arr2) {
while (val > 0) {
if (prefixes.contains(val)) {
maxLength = Math.max(maxLength, Integer.toString(val).length());
break; // Longest prefix for this number found
}
val /= 10;
}
}
return maxLength;
}
}
"""
Problem: LeetCode 3043 - Find the Length of the Longest Common Prefix
Difficulty: Medium
Language: Python
Author: CodeByTushu
"""
from typing import List
class Solution:
def longestCommonPrefix(self, arr1: List[int], arr2: List[int]) -> int:
prefixes = set()
# Generate and insert all prefixes from arr1
for val in arr1:
while val > 0:
prefixes.add(val)
val //= 10
max_length = 0
# Find the longest matching prefix for numbers in arr2
for val in arr2:
while val > 0:
if val in prefixes:
max_length = max(max_length, len(str(val)))
break # Longest prefix for this value found
val //= 10
return max_length
/**
* Problem: LeetCode 3043 - Find the Length of the Longest Common Prefix
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
#include <vector>
#include <unordered_set>
#include <string>
#include <algorithm>
using namespace std;
class Solution {
public:
int longestCommonPrefix(vector<int>& arr1, vector<int>& arr2) {
unordered_set<int> prefixes;
// Collect all numerical prefixes of arr1
for (int val : arr1) {
while (val > 0) {
prefixes.insert(val);
val /= 10;
}
}
int maxLength = 0;
// Match prefixes of numbers in arr2 against the set
for (int val : arr2) {
while (val > 0) {
if (prefixes.count(val)) {
maxLength = max(maxLength, static_cast<int>(to_string(val).length()));
break;
}
val /= 10;
}
}
return maxLength;
}
};
/**
* Problem: LeetCode 3043 - Find the Length of the Longest Common Prefix
* Difficulty: Medium
* Language: JavaScript
* Author: CodeByTushu
*/
/**
* @param {number[]} arr1
* @param {number[]} arr2
* @return {number}
*/
var longestCommonPrefix = function(arr1, arr2) {
const prefixes = new Set();
// Store all prefix integers from arr1
for (let val of arr1) {
while (val > 0) {
prefixes.add(val);
val = Math.floor(val / 10);
}
}
let maxLength = 0;
// Search for longest common prefix in arr2
for (let val of arr2) {
while (val > 0) {
if (prefixes.has(val)) {
maxLength = Math.max(maxLength, String(val).length);
break;
}
val = Math.floor(val / 10);
}
}
return maxLength;
};