Find the Length of the Longest Common Prefix

medium trie prefix

Problem

You are given two arrays of positive integers, arr1 and arr2. A common prefix of two numbers is a number formed by leading digits they share when written in decimal — for example, 565 and 5655 share the prefix 565. Considering every pair (x, y) with x from arr1 and y from arr2, return the number of digits in the longest common prefix among all pairs, or 0 if no pair shares even a first digit.

Inputarr1 = [1, 10, 100], arr2 = [1000]
Output3
The pair (100, 1000) shares the prefix "100", which has 3 digits — no other pair does better.

def longest_common_prefix(arr1, arr2):
    trie = {}
    for a in arr1:
        node = trie
        for d in str(a):
            node = node.setdefault(d, {})
    best = 0
    for b in arr2:
        node = trie
        length = 0
        for d in str(b):
            if d not in node:
                break
            node = node[d]
            length += 1
        best = max(best, length)
    return best
function longestCommonPrefix(arr1, arr2) {
  const trie = {};
  for (const a of arr1) {
    let node = trie;
    for (const d of String(a)) {
      node = node[d] || (node[d] = {});
    }
  }
  let best = 0;
  for (const b of arr2) {
    let node = trie, len = 0;
    for (const d of String(b)) {
      if (!(d in node)) break;
      node = node[d];
      len++;
    }
    best = Math.max(best, len);
  }
  return best;
}
int longestCommonPrefix(int[] arr1, int[] arr2) {
    Map<Character, Object> trie = new HashMap<>();
    for (int a : arr1) {
        Map<Character, Object> node = trie;
        for (char d : String.valueOf(a).toCharArray()) {
            node = (Map<Character, Object>) node.computeIfAbsent(d, k -> new HashMap<>());
        }
    }
    int best = 0;
    for (int b : arr2) {
        Map<Character, Object> node = trie;
        int len = 0;
        for (char d : String.valueOf(b).toCharArray()) {
            if (!node.containsKey(d)) break;
            node = (Map<Character, Object>) node.get(d);
            len++;
        }
        best = Math.max(best, len);
    }
    return best;
}
struct Node { Node* next[10] = {}; };

int longestCommonPrefix(vector<int>& arr1, vector<int>& arr2) {
    Node* trie = new Node();
    for (int a : arr1) {
        Node* node = trie;
        for (char d : to_string(a)) {
            int i = d - '0';
            if (!node->next[i]) node->next[i] = new Node();
            node = node->next[i];
        }
    }
    int best = 0;
    for (int b : arr2) {
        Node* node = trie;
        int len = 0;
        for (char d : to_string(b)) {
            int i = d - '0';
            if (!node->next[i]) break;
            node = node->next[i];
            len++;
        }
        best = max(best, len);
    }
    return best;
}
Time: O((n + m) · D) Space: O(n · D)