The Find the Length of the Longest Common Prefix interview question involves two arrays of positive integers, arr1 and arr2. You need to find the longest common prefix shared between any number from arr1 and any number from arr2. A prefix is the leading part of a number (e.g., the prefixes of 123 are 1, 12, and 123). You want to return the length of the longest such prefix.
This "Medium" difficulty problem is popular at companies like Uber, Databricks, and Meta. it's a test of your ability to perform efficient string or number matching. While you could compare every pair (), the problem challenges you to find an or solution using a Trie interview pattern or a Hash Set of all possible prefixes.
There are two effective patterns:
arr1. For each number, generate all its prefixes (e.g., 123 1, 12, 123) and add them to a HashSet.arr2. For each number, check its prefixes from longest to shortest.HashSet is a candidate for the longest common prefix.arr1 into a Trie (treating them as strings).arr2, traverse the Trie to see how deep you can go. The depth reached is the length of the common prefix.arr1 = [123, 456], arr2 = [12, 45]
arr2:
arr2:
arr1 with every in arr2, resulting in , which will time out.num /= 10).When searching for "Common Prefixes," always consider a Trie. Even if a Hash Set is easier to implement, mentioning a Trie shows you understand the data structure specifically designed for prefix operations.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Replace Words | Medium | Solve | |
| Shortest Uncommon Substring in an Array | Medium | Solve | |
| Short Encoding of Words | Medium | Solve | |
| Palindrome Pairs | Hard | Solve | |
| Add Bold Tag in String | Medium | Solve |