Find the Length of the Longest Common Prefix (LeetCode 3043): Solution and Explanation

Medium
Array
Hash Table
String
Trie

Given two arrays of positive integers, return the number of digits in the longest prefix shared by any number from the first array and any number from the second.

Intuition

Checking every pair costs n times m comparisons, which is far too slow at 5 * 10^4 numbers per side.

A common prefix of x and y is a path that both numbers trace from the root of a digit trie. Put every number of arr1 into one trie and all of their prefixes are stored at once.

Each number of arr2 then walks down the trie digit by digit. The depth where it runs out of edges is its longest common prefix with anything in arr1, and the answer is the deepest such walk.

Approach: Digit trie

  1. Create an empty trie whose edges are labeled with the digits 0 to 9.
  2. For each x in arr1, insert the decimal digits of x, creating nodes that do not exist yet.
  3. For each y in arr2, start at the root with depth 0 and follow its digits while an edge exists, adding 1 to depth per step.
  4. Keep best = max(best, depth) after each walk and return best.

Step-by-step example

arr1 = [1,10,100], arr2 = [1000]
  1. Insert 1: the trie gets the path 1.
  2. Insert 10: follow 1, then add a node for 0.
  3. Insert 100: follow 1 and 0, then add one more node for 0. The trie is a single chain 1 -> 0 -> 0.
  4. Walk 1000: digits 1, 0 and 0 all have edges, so depth reaches 3. The fourth digit 0 has no edge, so the walk stops.
  5. best = 3, so return 3.

Code: Python, Java, C++

1class Solution:
2    def longestCommonPrefix(self, arr1: List[int], arr2: List[int]) -> int:
3        root = {}
4        for x in arr1:
5            node = root
6            for ch in str(x):
7                node = node.setdefault(ch, {})
8        best = 0
9        for y in arr2:
10            node = root
11            depth = 0
12            for ch in str(y):
13                if ch not in node:
14                    break
15                node = node[ch]
16                depth += 1
17            best = max(best, depth)
18        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O((n + m) * D)

Each of the n numbers in arr1 is inserted and each of the m numbers in arr2 is walked, and each touches at most D = 9 digits.

Space

O(n * D)

In the worst case every inserted digit creates a new trie node.

Other approaches

Hash set of prefixes (time O((n + m) * D), space O(n * D))

Divide every x in arr1 by 10 repeatedly and store each prefix in a set. For each y in arr2, strip digits from the right until the value is in the set; its digit count is the candidate.

Compare every pair (time O(n * m * D), space O(D))

Convert both numbers to strings and count matching leading characters for all n * m pairs. Simple, but too slow for the largest inputs.

Common mistakes

  • Returning the prefix itself instead of its length in digits.
  • Counting the walk one step too far: depth should increase only after an edge is found.
  • Treating the problem as a longest common prefix of strings in one array; here the two numbers must come from different arrays.

Frequently asked questions

Why build the trie from arr1 and not arr2?

Either side works, since the relation is symmetric. Building from the smaller array saves memory, but the time bound is the same.

Do numbers in the same array ever compare with each other?

No. Only arr1 is in the trie and only arr2 walks it, so every walk measures a pair with one number from each array.

Can leading zeros cause trouble?

No. All values are positive integers, so their decimal strings never start with 0 and each number maps to exactly one path.

Is the hash set approach really as fast?

Yes asymptotically, since each number has at most 9 prefixes. The trie is easier to picture and stops at the first missing digit instead of probing every length.