Katkat

Find the Longest Common Digit Prefix Across Two Arrays

Hudson River TradingSoftware Engineer · Technical Screen

Last updated

Tests candidate's ability to efficiently match string/digit prefixes between two collections of integers using hash sets or a prefix tree (Trie).

Longest Common Digit Prefix Across Two Arrays

Given two arrays of positive integers arr1 and arr2, find the length of the longest common decimal digit prefix between any pair of numbers (x, y) where x is in arr1 and y is in arr2.

A prefix of an integer is a sequence formed by taking leading digits of its decimal representation. If there is no common prefix between any pair, return 0.

Function Signature

def longest_common_digit_prefix(arr1: list[int], arr2: list[int]) -> int:
    pass

Input and Output

  • Input: Two lists of positive integers, arr1 and arr2.
  • Output: An integer representing the maximum length of a shared digit prefix between an element of arr1 and an element of arr2.

Examples

Example 1:

Input: arr1 = [1, 10, 100], arr2 = [1000]
Output: 3
Explanation: 
The integer 100 from arr1 and 1000 from arr2 share the common prefix "100", which has length 3.

Example 2:

Input: arr1 = [1234, 5678], arr2 = [567, 999]
Output: 3
Explanation: 
The integer 5678 from arr1 and 567 from arr2 share the common prefix "567", which has length 3.

Example 3:

Input: arr1 = [12, 34], arr2 = [56, 78]
Output: 0
Explanation: 
No numbers across the two arrays share any leading digits.

Constraints

  • 1 <= len(arr1), len(arr2) <= 5 * 10^4
  • 1 <= arr1[i], arr2[i] <= 10^8

Edge Cases to Consider

  • Single-digit numbers where the maximum prefix length is at most 1.
  • No common prefix exists between any elements (returns 0).
  • Duplicate values within the same array or across arrays.

Hints

Hint 1

A brute-force pair comparison takes O(len(arr1) * len(arr2)) time, which will exceed typical time limits given arrays up to size 50,000.

Hint 2

Notice that each integer has at most 8 or 9 digits, so it has at most 9 prefixes.

Hint 3

Store all prefixes of numbers from one array in a hash set or a Trie, then test prefixes of numbers from the other array in O(digits) per number.

Follow-up questions

  • How does the memory footprint of a hash set containing all prefixes compare to a 10-ary digit Trie?
  • If arr1 is updated continuously via stream insertion, how would you maintain the query efficiently?
  • Can you solve this without converting integers to strings, using only arithmetic operations (division and modulo)?