Closed mah-shamim closed 2 hours ago
We can utilize a HashSet to store the prefixes from one array and then check for those prefixes in the second array.
Generate Prefixes: For each number in arr1
and arr2
, 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 a HashSet
to store all prefixes of numbers in arr1
ensures fast lookups when checking prefixes from arr2
.
Find Longest Common Prefix: For each number in arr2
, generate its prefixes and check if any of these prefixes exist in the HashSet
from step 2. Track the longest prefix found.
Return the Length of the Longest Common Prefix: If a common prefix is found, return its length; otherwise, return 0
.
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
?>
HashSet Creation:
$prefixSet
to hold all possible prefixes of numbers in arr1
.arr1
, convert it to a string, and extract all its prefixes using the substr
function. Each prefix is stored in the $prefixSet
.Prefix Checking:
arr2
, converting it to a string as well.arr2
, we again extract all possible prefixes.$prefixSet
, we check if its length is greater than the current maximum length found ($maxLength
).Return the Result:
arr1
and arr2
respectively. This is because we are processing every number and their prefixes.This solution is efficient and works well within the provided constraints.
Discussed in https://github.com/mah-shamim/leet-code-in-php/discussions/605
1 <= arr1.length, arr2.length <= 5 * 104
-1 <= arr1[i], arr2[i] <= 108
**Hint:** 1. Put all the possible prefixes of each element in `arr1` into a HashSet. 2. For all the possible prefixes of each element in `arr2`, check if it exists in the HashSet.