Leetcode 3043: Find the Length of the Longest Common Prefix

grid47
grid47
Exploring patterns and algorithms
Jan 7, 2024 7 min read

You are given two arrays arr1 and arr2 containing positive integers. Your task is 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. A prefix of a number is any integer formed by one or more digits starting from its leftmost digit. For example, 123 is a prefix of 12345, but 234 is not. If no common prefix exists for any pair, return 0.
Problem
Approach
Steps
Complexity
Input: You are given two arrays `arr1` and `arr2` containing positive integers.
Example: arr1 = [1, 10, 100], arr2 = [1000]
Constraints:
• 1 <= arr1.length, arr2.length <= 5 * 10^4
• 1 <= arr1[i], arr2[i] <= 10^8
Output: Return an integer representing the length of the longest common prefix among all pairs of integers `(x, y)` where `x` belongs to `arr1` and `y` belongs to `arr2`.
Example: For input arr1 = [1, 10, 100] and arr2 = [1000], the output is 3, as the longest common prefix is '100'.
Constraints:
• If no common prefix exists for any pair, return 0.
Goal: To solve the problem, we need to find the longest common prefix between all pairs of integers where one integer is from `arr1` and the other is from `arr2`. We can do this by checking all pairs and calculating the longest prefix for each pair.
Steps:
• Iterate over all integers in `arr1` and `arr2`.
• For each pair of integers `(x, y)`, compare their digits starting from the leftmost digit to find the longest common prefix.
• Store and update the maximum length of the common prefix encountered.
Goal: The constraints ensure that the arrays are large, but the integers themselves are manageable in terms of size.
Steps:
• 1 <= arr1.length, arr2.length <= 5 * 10^4
• 1 <= arr1[i], arr2[i] <= 10^8
Assumptions:
• All elements in both arrays are positive integers.
• No number will have more than 8 digits.
Input: arr1 = [1, 10, 100], arr2 = [1000]
Explanation: The longest common prefix between the numbers in `arr1` and `arr2` is 100, found between 100 from `arr1` and 1000 from `arr2`. Hence, the output is 3.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus