KatInterview

Longest Shared Leading-Digit Sequence Between Two Integer Lists

StringsAuto-graded · 23 test cases
MediumAuto-gradedStringsstringsarrayshashing

Last updated

Tests whether a candidate can avoid brute-force pair comparison by exploiting bounded digit counts to match prefixes efficiently with a hash set.

Longest Shared Leading-Digit Sequence Between Two Integer Lists

You are given two lists of positive integers, nums1 and nums2. Your task is to find the length of the longest leading-digit sequence that appears as a prefix in at least one number from nums1 and also as a prefix in at least one number from nums2.

A decimal prefix of a positive integer is any string of its leading digits in base 10. For example, the integer 4729 has the prefixes "4", "47", "472", and "4729".

If no such shared prefix exists across any pairing, return 0.

Input and Output

  • Input: Two lists of positive integers, nums1 and nums2.
  • Output: A single integer — the maximum length of any digit string that is a prefix of some element in nums1 and simultaneously a prefix of some element in nums2.

Constraints

  • 1 <= len(nums1), len(nums2) <= 5 * 10^4
  • 1 <= nums1[i], nums2[i] <= 10^8
  • Elements within a list are not necessarily distinct.

Examples

Example 1

Input: max_shared_digit_prefix_length([1, 10, 100], [1000])

Output: 3

Example 2

Input: max_shared_digit_prefix_length([1234, 5678], [567, 999])

Output: 3

Example 3

Input: max_shared_digit_prefix_length([12, 34], [56, 78])

Output: 0

Hints

Hint 1

A brute-force approach checks every pair (x, y) — up to 2.5 billion comparisons at the maximum sizes. Think about what you can precompute from one list so that processing the other list becomes fast lookups instead of pairwise comparisons.

Hint 2

Each number is at most 10^8, which means at most 9 digits, so it has at most 9 prefixes. Store every prefix of every number in nums1 in a hash set, then probe each prefix of each number in nums2 against that set.

Hint 3

Once you have the prefix set built from nums1, iterate through nums2 and for each number check each of its prefixes from shortest to longest (or longest to shortest). The answer is the maximum length prefix that appears in both sets.