← Questions

Longest common prefix between numbers of two arrays

0
DatabricksCodingLast asked Sep 2024

A coding interview question asked in Databricks's online assessment, last asked Sep 2024. It tests trie, hash sets and strings.

You get two arrays of positive integers. For every pair made of one number from each array, look at the longest run of leading decimal digits the two numbers share. Return the longest such length over all pairs, or 0 if no pair even shares a first digit.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • longest_common_prefix(first: list[int], second: list[int]) -> int

Example

longest_common_prefix([25, 288, 2655, 54546, 54, 555], [2, 255, 266, 244, 26, 5, 54547])  ->  4    # 54546 and 54547 share 5454
longest_common_prefix([25, 288, 2655, 544, 54, 555], [2, 255, 266, 244, 26, 5, 5444444])  ->  3    # 544 is a prefix of 5444444
longest_common_prefix([817, 99], [1999, 1909])                                            ->  0

Constraints

  • Up to 5 × 10^4 numbers per array; each is between 1 and 10^9.

Clarifying questions

  • Is the prefix measured in decimal digits?
  • Can numbers repeat?
  • Should I return the prefix itself or its length?

What a strong answer covers

  • Why comparing every pair (up to 2.5 × 10^9 pairs) is too slow.
  • Storing every prefix of every number in the first array in a hash set (at most 10 per number), then checking each prefix of each number in the second array, longest first; O((n + m) × 10) time.
  • A trie of digits as the alternative, and the memory it uses.
  • Working on strings or by integer division (x // 10) to get prefixes.
  • Tests: no shared first digit, a whole number being a prefix of another, equal numbers.

Follow-ups

  • Return the pair that achieves the maximum.
  • Count the pairs whose common prefix has length at least L.
  • The numbers are given as very long digit strings.

Where it's asked

What it tests

trie · hash sets · strings

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding