search
HomeBackend DevelopmentPHP TutorialFind the Length of the Longest Common Prefix

Find the Length of the Longest Common Prefix

3043. Find the Length of the Longest Common Prefix

Difficulty: Medium

Topics: Array, Hash Table, String, Trie

You are given two arrays with positive integers arr1 and arr2.

A prefix of a positive integer is an integer formed by one or more of its digits, starting from its leftmost digit. For example, 123 is a prefix of the integer 12345, while 234 is not.

A common prefix of two integers a and b is an integer c, such that c is a prefix of both a and b. For example, 5655359 and 56554 have a common prefix 565 while 1223 and 43456 do not have a common prefix.

You need to find the length of the longest common prefix between all pairs of integers (x, y) such that x belongs to arr1 and y belongs to arr2.

Return the length of the longest common prefix among all pairs. If no common prefix exists among them, return 0.

Example 1:

  • Input: arr1 = [1,10,100], arr2 = [1000]
  • Output: 3
  • Explanation: There are 3 pairs (arr1[i], arr2[j]):
    • The longest common prefix of (1, 1000) is 1.
    • The longest common prefix of (10, 1000) is 10.
    • The longest common prefix of (100, 1000) is 100.
    • The longest common prefix is 100 with a length of 3.

Example 2:

  • Input: arr1 = [1,2,3], arr2 = [4,4,4]
  • Output: 4
  • Explanation: There exists no common prefix for any pair (arr1[i], arr2[j]), hence we return 0.
    • Note that common prefixes between elements of the same array do not count.

Constraints:

  • 1 4
  • 1 8

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.

Solution:

We can utilize a HashSet to store the prefixes from one array and then check for those prefixes in the second array.

Approach:

  1. 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.

  2. 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.

  3. 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.

  4. 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 /**
 * @param Integer[] $arr1
 * @param Integer[] $arr2
 * @return Integer
 */
function longestCommonPrefix($arr1, $arr2) {
    ...
    ...
    ...
    /**
     * go to ./solution.php
     */
}

// 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:

  1. HashSet Creation:

    • We first create an associative array $prefixSet to hold all possible prefixes of numbers in arr1.
    • We iterate through each number in arr1, convert it to a string, and extract all its prefixes using the substr function. Each prefix is stored in the $prefixSet.
  2. Prefix Checking:

    • Next, we loop through each number in arr2, converting it to a string as well.
    • For each number in arr2, we again extract all possible prefixes.
    • If a prefix exists in $prefixSet, we check if its length is greater than the current maximum length found ($maxLength).
  3. Return the Result:

    • Finally, we return the length of the longest common prefix found.

Complexity:

  • Time Complexity: O(n * m) where n and m are the lengths of arr1 and arr2 respectively. This is because we are processing every number and their prefixes.
  • Space Complexity: O(p) where p is the total number of prefixes stored in the HashSet.

This solution is efficient and works well within the provided constraints.

Contact Links

If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!

If you want more helpful content like this, feel free to follow me:

  • LinkedIn
  • GitHub

The above is the detailed content of Find the Length of the Longest Common Prefix. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools