Find the Length of the Longest Common Prefix
Medium
Topics
You are given two arrays of positive integers, a and b.
A common prefix of two integers is a prefix they share when both are written in decimal with no leading zeros: 5655359 and 56554 share 565, which has length 3, while 1223 and 43456 share nothing.
Return the length of the longest common prefix over all pairs (x, y) with x from a and y from b, or 0 if no pair shares a prefix.
Example 1
100 counts as a prefix of 1000 even though it is a smaller number. The shaded pair 100 and 1000 share 3 digits, and no other pair shares more.Input: a = [1,10,100], b = [1000] Output: 3 Explanation: 100 and 1000 share the prefix 100. The pair (10, 1000) shares only 10, and (1, 1000) only 1.
Example 2
Input: a = [1,2,3], b = [4,4,4] Output: 0 Explanation: No number in a starts with a 4, so no pair shares even one digit.
Example 3
Input: a = [1], b = [1] Output: 1 Explanation: The two numbers are equal, so the whole of one is a prefix of the other.
Constraints
- 1 <= a.length, b.length <= 5 * 10^4
- 1 <= a[i], b[i] <= 10^8
Editorial — intuition, approach, complexity and pitfalls
Intuition
Comparing every pair digit by digit is the obvious route and it does the same work repeatedly: if three numbers in a all start with 12, each of them re-establishes that fact against every number in b.
The way out is to stop thinking about pairs. Collect every prefix of every number in a into a set — for 100 that is 1, 10 and 100. Then for each number in b, walk its own prefixes from the shortest up and ask whether the set contains them. The longest hit is that number’s best, and the answer is the largest over all of b.
This is cheap because a number under 10^8 has at most 9 prefixes, so the set holds at most 9 entries per element of a and each element of b costs at most 9 lookups. A trie expresses the same idea with less memory, and the set version is the one worth reaching for first.
Approach
- Build a set of every prefix of every number in
a. Generate a number’s prefixes by repeatedly dividing it by 10 — or by taking the prefixes of its decimal string. - For each number in
b, take its prefixes in increasing length and check each against the set. - Track the length of the longest prefix found in the set across all of
b. - Return 0 if nothing matched, which falls out of initialising the best length to 0.
Walkthrough
a = [1, 10, 100]
b = [1000]
prefixes of a
1 -> 1
10 -> 1, 10
100 -> 1, 10, 100
set = {1, 10, 100}
prefixes of 1000, shortest first
1 in the set length 1
10 in the set length 2
100 in the set length 3
1000 not in set stop looking
answer 3Complexity
- Time — O((n + m) * d): d is the digit count, at most 9 here, so this is linear in the inputs for every practical purpose. The pairwise comparison is O(n * m * d).
- Space — O(n * d): the prefix set holds at most one entry per digit of each element of a.
Common Pitfalls
- Returning the longest prefix for the first matching pair rather than the maximum over all pairs.
- Stopping at the first prefix of a number in
bthat is absent. That is a valid shortcut — if12is not a prefix then neither is123— but only because prefixes are nested; applying the same logic across different numbers is not valid. - Comparing the numbers rather than their digit strings:
100is not numerically a prefix of1000, it is a textual one. - Treating a number as a prefix of a shorter number.
1000and100share 3 digits, not 4.
Full Solution — all languages
class Solution:
def longestCommonPrefix(self, a, b):
prefixes = set()
for value in a:
while value:
prefixes.add(value)
value //= 10
best = 0
for value in b:
text = str(value)
for length in range(1, len(text) + 1):
if int(text[:length]) in prefixes:
best = max(best, length)
return bestimport java.util.*;
class Solution {
public int longestCommonPrefix(int[] a, int[] b) {
Set<Integer> prefixes = new HashSet<>();
for (int value : a) {
while (value > 0) {
prefixes.add(value);
value /= 10;
}
}
int best = 0;
for (int value : b) {
String text = String.valueOf(value);
for (int length = 1; length <= text.length(); length++) {
if (prefixes.contains(Integer.parseInt(text.substring(0, length)))) {
best = Math.max(best, length);
}
}
}
return best;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int longestCommonPrefix(vector<int>& a, vector<int>& b) {
unordered_set<int> prefixes;
for (int value : a) {
while (value > 0) {
prefixes.insert(value);
value /= 10;
}
}
int best = 0;
for (int value : b) {
string text = to_string(value);
for (size_t length = 1; length <= text.size(); length++) {
if (prefixes.count(stoi(text.substr(0, length)))) best = max(best, (int)length);
}
}
return best;
}
};/**
* @param {number[]} a
* @param {number[]} b
* @return {number}
*/ var longestCommonPrefix = function(a, b) {
const prefixes = new Set();
for (let value of a) {
while (value > 0) {
prefixes.add(value);
value = Math.floor(value / 10);
}
}
let best = 0;
for (const value of b) {
const text = String(value);
for (let length = 1; length <= text.length; length++) {
if (prefixes.has(parseInt(text.slice(0, length), 10))) best = Math.max(best, length);
}
}
return best;
};