3043. Find the Length of the Longest Common Prefix #605
-
Topics: You are given two arrays with positive integers A prefix of a positive integer is an integer formed by one or more of its digits, starting from its leftmost digit. For example, A common prefix of two integers You need to find the length of the longest common prefix between all pairs of integers Return the length of the longest common prefix among all pairs. If no common prefix exists among them, return Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can utilize a HashSet to store the prefixes from one array and then check for those prefixes in the second array. Approach:
Let's implement this solution in PHP: 3043. Find the Length of the Longest Common Prefix <?php
function longestCommonPrefix($arr1, $arr2) {
$prefixSet = [];
// Step 1: Generate all prefixes for elements in arr1 and store them in a HashSet
foreach ($arr1 as $num) {
$str = (string)$num; // Convert to string to extract prefixes
for ($i = 1; $i <= strlen($str); $i++) {
$prefixSet[substr($str, 0, $i)] = true; // Store the prefix in the HashSet
}
}
$maxLength = 0;
// Step 2: Check prefixes of elements in arr2 against the HashSet
foreach ($arr2 as $num) {
$str = (string)$num; // Convert to string to extract prefixes
for ($i = 1; $i <= strlen($str); $i++) {
$prefix = substr($str, 0, $i); // Get the current prefix
if (isset($prefixSet[$prefix])) {
// If the prefix exists in arr1, update the maxLength
$maxLength = max($maxLength, strlen($prefix));
}
}
}
return $maxLength; // Return the length of the longest common prefix
}
// Example usage:
$arr1 = [1, 10, 100];
$arr2 = [1000];
echo longestCommonPrefix($arr1, $arr2); // Output: 3
$arr1 = [1, 2, 3];
$arr2 = [4, 4, 4];
echo longestCommonPrefix($arr1, $arr2); // Output: 0
?> Explanation:
Complexity:
This solution is efficient and works well within the provided constraints. |
Beta Was this translation helpful? Give feedback.
We can utilize a HashSet to store the prefixes from one array and then check for those prefixes in the second array.
Approach:
Generate Prefixes: For each number in
arr1
andarr2
, generate all possible prefixes. A prefix is formed by one or more digits starting from the leftmost digit.Store Prefixes of
arr1
in a Set: Using aHashSet
to store all prefixes of numbers inarr1
ensures fast lookups when checking prefixes fromarr2
.Find Longest Common Prefix: For each number in
arr2
, generate its prefixes and check if any of these prefixes exist in theHashSet
from step 2. Track the longest prefix found.Return the Length of the Longest Common Prefix: If a common prefix is found, retu…